How to handle empty (none) tuple returned from python function

I have a function that returns either a tuple or None. How should Caller handle this condition?

def nontest(): return None x,y = nontest() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not iterable 
+6
source share
3 answers

EAFP :

 try: x,y = nontest() except TypeError: # do the None-thing here or pass 

or without try-except:

 res = nontest() if res is None: .... else: x, y = res 
+10
source

What about:

 x,y = nontest() or (None,None) 

If nontest returns a tuple of two elements, as it should be, then x and y are assigned to the elements in the tuple. Otherwise, x and y are each assigned to none. The disadvantage of this is that you cannot run special code if nontest returns empty (the above answers may help you if that is your goal). The surface is that it is clean and easy to read / maintain.

+6
source

If you can change the function itself, it's probably best to think about it throwing an appropriate exception instead of returning None to signal an error. Then the caller should just try / except .

If None does not signal an error, you need to completely rethink your semantics.

+5
source

Source: https://habr.com/ru/post/944940/


All Articles