Skip to content

Instantly share code, notes, and snippets.

@keenhenry
Created March 31, 2016 19:27
Show Gist options
  • Save keenhenry/0883da91cd80a9a1290e7aa0b6bb2fd6 to your computer and use it in GitHub Desktop.
Save keenhenry/0883da91cd80a9a1290e7aa0b6bb2fd6 to your computer and use it in GitHub Desktop.
Python Scopes Quirks
#!/usr/bin/env python
# name binding always creates a name in the local scope
ng = 'a global'
def f():
# without the following commented out line, UnboundLocalError will throw
# global ng
nl = 2
print ng, nl
ng = 3
print ng, nl
f()
print ng
# class variable not directly accessible from within its methods
class Foo(object):
nclass = 'pig'
def f(self):
self.__class__.nclass
# the following statement will give you UnboundLocalError error
# print nclass
foo = Foo()
foo.f()
# for-loop leak loop variable outside the loop:
for i in xrange(10):
print i,
print '\ni after loop:', i
# cannot rebind nonlocal variables within a nested function in Python 2
# Python 3 has nonlocal keyword that addresses this problem
a_var = 'global value'
def outer():
a_var = 'enclosed value'
def inner():
a_var = 'modified enclosed value'
print(a_var)
inner()
print a_var
outer()
print a_var
# try-except-finally also leaks variables
try:
f = open('sometext.txt', 'r')
for line in f: print line,
except Exception as e:
print e
finally:
f.close()
print f
print line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment