cs107-lecture-examples

Example codes used during Harvard CS107 lectures
git clone https://git.0xfab.ch/cs107-lecture-examples.git
Log | Files | Refs | README | LICENSE

nonlocal.py (1200B)


      1 #!/usr/bin/env python3
      2 import dis
      3 
      4 
      5 def f_local_unbound(x):
      6     def closure(y):
      7         x -= y  # shadows `x` in the outer function
      8         return y
      9 
     10     return closure
     11 
     12 
     13 def f_local_bound(x):
     14     def closure(y):
     15         y = x  # `x` does not shadow itself because it is not redefined in local scope
     16         return y
     17 
     18     return closure
     19 
     20 def f_nonlocal(x):
     21     def closure(y):
     22         nonlocal x
     23         x -= y
     24         return x
     25 
     26     return closure
     27 
     28 
     29 def f_global(x):
     30     def closure(y):
     31         global x
     32         x -= y
     33         return x
     34 
     35     return closure
     36 
     37 
     38 def disassemble(f, val=0):
     39     c = f(val)
     40     # Tuple containing names of local variables referenced in nested functions
     41     print(f"{'Cell vars `' + f.__name__ + '`:':<32}{f.__code__.co_cellvars}")
     42     # Tuple containing names of local variables in outer function
     43     print(f"{'Local vars `' + f.__name__ + '`:':<32}{f.__code__.co_varnames}")
     44     # Tuple containing names of local variables in closure
     45     print(f"{'Local vars `' + c.__name__ + '`:':<32}{c.__code__.co_varnames}")
     46 
     47     print('Disassembly:')
     48     dis.dis(c)
     49     print('')
     50 
     51 
     52 disassemble(f_local_unbound)
     53 disassemble(f_local_bound)
     54 disassemble(f_nonlocal)
     55 disassemble(f_global)