Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between no returned value and return None

Tags:

python

Is there a way to differentiate these two returned values?

>>> sort([1, 2, 3])
None

>>> dict(a=1).get('b')
None

The first returns None because there is no returned value. The second returns None as the returned value.

like image 567
nathancahill Avatar asked Feb 13 '23 09:02

nathancahill


2 Answers

A function returning None, just returning or allowing execution to reach the end of the function is basically the same thing.

Consider the following functions:

def func1():
        return None

def func2():
        pass

def func3():
        return

If we now dissasemble the functions' bytecode (the dismodule can do that), we see the following

func1():
  2           0 LOAD_CONST               0 (None)
              3 RETURN_VALUE        
func2():
  5           0 LOAD_CONST               0 (None)
              3 RETURN_VALUE        
func3():
  8           0 LOAD_CONST               0 (None)
              3 RETURN_VALUE        

The functions are identical. Thus there is no way you could distinguish between them, even by inspecting the functions themselves.

like image 87
Krumelur Avatar answered Feb 14 '23 22:02

Krumelur


No, there is not. The following functions all return the same value, None:

def a(): return None  # Explicitly return, explicitly with the value None
def b(): return       # Explicitly return, implicitly with the value None
def c(): pass         # Implicitly return, implicitly with the value None

You can't differentiate between the values returned by these functions because they all return the same thing.

Further reading: Python — return, return None, and no return at all

like image 38
cdhowie Avatar answered Feb 14 '23 22:02

cdhowie