Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning None or a tuple and unpacking

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 ?

like image 236
Stefano Borini Avatar asked Aug 13 '09 22:08

Stefano Borini


People also ask

Is unpacking possible in a tuple?

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.

What is unpacking in tuple?

Unpacking a tuple means splitting the tuple's elements into individual variables. For example: x, y = (1, 2) Code language: Python (python)

Is it good practice to return none in 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.

Does tuple unpacking work with lists?

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 [] .


1 Answers

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.

like image 80
Amber Avatar answered Oct 06 '22 16:10

Amber