4

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.

nathancahill
  • 10,452
  • 9
  • 51
  • 91

3 Answers3

6

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.

Krumelur
  • 31,081
  • 7
  • 77
  • 119
1

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

Community
  • 1
  • 1
cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

If you're specifically asking about dict.get():

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

Well written "lookup" APIs will either work that way (let you pass a custom 'not found' value) or raise some exception.

Else, well, no, None is None, period.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118