bwangel23
12/5/2016 - 12:04 PM

locals.py

In [12]: def test():
    ...:     if False:
    ...:         global x 
    ...:         x = 10
    ...:     print(x)
    ...:     
    ...:     

In [13]: test()
10

In [14]: dis.dis(test)
  5           0 LOAD_GLOBAL              0 (print)
              3 LOAD_GLOBAL              1 (x)
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

In [15]: def test():
    ...:     if False:
    ...:         x = 10
    ...:     print(x)
    ...:     

In [16]: test()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-16-ea594c21b25d> in <module>()
----> 1 test()

<ipython-input-15-3f437de0992e> in test()
      2     if False:
      3         x = 10
----> 4     print(x)
      5 

UnboundLocalError: local variable 'x' referenced before assignment

In [17]: dis.dis(test)
  4           0 LOAD_GLOBAL              0 (print)
              3 LOAD_FAST                0 (x)
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE