I am always annoyed by this fact:
$ cat foo.py def foo(flag): if flag: return (1,2) else: return None first, second = foo(True) first, second = foo(False) $ python foo.py Traceback (most recent call last): File "foo.py", line 8, in <module> first, second = foo(False) TypeError: 'NoneType' object is not iterable
The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like
values = foo(False) if values is not None: first, second = values
Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?
In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.
Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)
Whether or not to return None explicitly is a personal decision. However, you should consider that in some cases, an explicit return None can avoid maintainability problems. This is especially true for developers who come from other programming languages that don't behave like Python does.
Unpack a nested tuple and list. You can also unpack a nested tuple or list. If you want to expand the inner element, enclose the variable with () or [] .
Well, you could do...
first,second = foo(True) or (None,None) first,second = foo(False) or (None,None)
but as far as I know there's no simpler way to expand None to fill in the entirety of a tuple.
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