Home>

How are the two functions different?

def f (x = None):
     if x:
         return x
     else:
         pass
def g (x = None):
     if x is not None:
         return x
     else:
         pass
f (5) # 5
g (5) # 5
f () # None
g () # None

Check withdis.dis

dis.dis (f)
"" "
  2 0 LOAD_FAST 0 (x)
              2 POP_JUMP_IF_FALSE 8
  3 4 LOAD_FAST 0 (x)
              6 RETURN_VALUE
  5&​​gt;>8 LOAD_CONST 0 (None)
             10 RETURN_VALUE
"" "
dis.dis (g)
"" "
              2 LOAD_CONST 0 (None)
              4 COMPARE_OP 9 (is not)
              6 POP_JUMP_IF_FALSE 12
  3 8 LOAD_FAST 0 (x)
             10 RETURN_VALUE
  5&​​gt;>12 LOAD_CONST 0 (None)
             14 RETURN_VALUE
"" "
It looks like

is different

If the results you get are generally the same, theg ()function, which has more processing such asLOAD, is obviously more verbose.

  • Answer # 1

    Whether it is

    NoneorFalseis a completely different matter.

    Reference:
    4. Built-in types — Python 3.6.5 documentation 4.1. Truth value determination

      

    Also, if you are actually writing if x is not None, be careful if you write if x-for example, a variable or argument whose default value is None will have something else When testing whether it is set. This "different value" may be a type (like a container) that evaluates to False in a Boolean context!
      Introduction — pep8-en 1.0 Documentation Recommendations for Programming   

    As an aside, g seems to be a good identity function.

  • Answer # 2

    There are other elements than False that are judged by False.

    def f (x = None):
         if x:
             return x
         else:
             pass
    def g (x = None):
         if x is not None:
             return x
         else:
             pass
    f (0) # None
    g (0) # 0
    In addition to

    0, empty sequences are also applicable. Of course, False itself.