import __builtin__ def scope(varname, local_scope, global_scope): if varname in local_scope: return '%s: local variable' % varname elif varname in global_scope: return '%s: global variable' % varname elif varname in dir(__builtin__): return '%s: built-in variable' % varname else: return '%s: not defined' % varname # global variable (but local for module scope) global_var = 1 print scope('global_var', locals(), globals()) # built-in function print scope('sum', locals(), globals()) print def fun(): # defined in function block, hence local in this scope # and all nested scopes fun_var = 1 print 'fun: %s' % scope('fun_var', locals(), globals()) # defined in module block, hence global in this scope print 'fun: %s' % scope('global_var', locals(), globals()) print def inner_with_free(): # `fun_var` is a free variable used in inner function # `inner_with_free` # This variable is resolved using nearest enclosing block, # thus `fun` function block print 'inner_with_free: fun_var =', fun_var print 'inner_with_free: %s' % scope('fun_var', locals(), globals()) inner_var = 1 print 'inner_with_free: %s' % scope('inner_var', locals(), globals()) print def inner_without_free(): # `fun_var` is defined in the `inner_without_free` function block # (see below), hence it is NOT resolved using outer function block # `fun_var` belongs to `inner_without_free` function block, # but it is not defined (bound) yet ... print 'inner_without_free: %s' % scope('fun_var', locals(), globals()) inner_var = 1 print 'inner_without_free: %s' % scope('inner_var', locals(), globals()) # ... `fun_var` definition fun_var = 1 print 'inner_without_free: %s' % scope('fun_var', locals(), globals()) print def inner_rebinding_free(): # `fun_var` is defined in the `inner_rebinding_free` function block # (see below), hence it is NOT resolved using outer function block, # `fun_var` belongs to `inner_rebinding_free` function block, # but it is not defined (bound) yet ... # (using definitons from different scopes in one function block # is deliberately forbidden) try: print 'fun_var =', fun_var except UnboundLocalError: print 'inner_rebinding_free: local variable can not be resolved' print 'inner_rebinding_free: %s' % scope('fun_var', locals(), globals()) inner_var = 1 print 'inner_rebinding_free: %s' % scope('inner_var', locals(), globals()) # ... `fun_var` defintion fun_var = 1 print 'inner_rebinding_free: %s' % scope('fun_var', locals(), globals()) print inner_with_free() inner_without_free() inner_rebinding_free() if __name__ == '__main__': fun()