Are there any downsides to using an empty tuple as a default for an iterable argument to a function? Assuming that what you want in the function is an immutable iterable. e.g.
def foo(a, b=()): print a for x in b: print x
I can't seem to find many examples of this use case.
A tuple can be an argument, but only one - it's just a variable of type tuple . In short, functions are built in such a way that they take an arbitrary number of arguments. The * and ** operators are able to unpack tuples/lists/dicts into arguments on one end, and pack them on the other end.
You can initialize an empty tuple by having () with no values in them. You can also initialize an empty tuple by using the tuple function. A tuple with values can be initialized by making a sequence of values separated by commas.
Tuples represent arbitrary sequences of values. When you need to describe an empty sequence of values, you can use an empty tuple.
How to create an empty tuple in python. To create an empty tuple in Python, use a empty round brackets ” () “ with no items in it. After writing the above code (create an empty tuple in python), Ones you will print “my_tuple” then the output will appear as a “ () ”. Here, an empty tuple is created with no object in it.
I can't think of any downsides, for when you need an immutable iterable. I think it just isn't used because the default_list=None
and default_list = default_list or None
pattern is what is used for mutable iterables, and people don't bother to change it (as there is no real need) in the less frequently occuring cases when the iterable is immutable. There is certainly no unexpected behaviour as with mutable default arguments.
There are no intrinsic problems with designing your default to be an immutable empty tuple. However, it could be considered an non-intuitive design approach. Any references to specific locations in the tuple would cause an exception to be raised. If you are careful enough with creating argument checks then this will not be a problem, but if you build the rest of your code to expect data from specific locations and don't verify the tuple is empty then this will cause errors.
It depends on what your goal is for the argument. An empty list would have more obvious applications for a default argument (at least those that modify the list in some way), but an empty immutable tuple would not have any intuitive uses as a default besides indicating that no argument was given.
The typical approach for default arguments would be to set them to None which makes it perfectly clear when the arguments have not been set:
def foo(a, b=None):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With