Differentiate between return value and return No

Is there a way to differentiate these two return values?

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

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

The first returns Nonebecause there is no return value. The second returns Noneas the return value.

+4
source share
3 answers

A function that returns None, simply returns, or allows execution to reach the end of the function is basically the same.

Consider the following functions:

def func1():
        return None

def func2():
        pass

def func3():
        return

If now we delete the function bytecode (the module discan do this), 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, you cannot distinguish between them, even by checking the functions themselves.

+6
source

, . , 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

, , .

: Python - , None

+1

If you specifically ask a question about dict.get():

sentinel = object()
dict(a=1).get("b", sentinel)

Well-written search APIs will either work this way (letting you pass in a custom value of "not found") or throw some sort of exception.

The rest, well, no, Nonethere is None, period.

+1
source

All Articles