Skip to content

Instantly share code, notes, and snippets.

@rduplain
Created March 1, 2013 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rduplain/5065520 to your computer and use it in GitHub Desktop.
Save rduplain/5065520 to your computer and use it in GitHub Desktop.
A look at lexical scoping of functions defined inside for-loops, in Python.
"A look at lexical scoping of functions defined inside for-loops, in Python."
import functools
def foo():
return 'foo'
def bar():
return 'bar'
def quux():
return 'quux'
def scan(context=globals()):
fns = {}
for name in ('foo', 'bar', 'quux'):
fn = context[name]
@functools.wraps(fn)
def handle(*a, **kw):
return '%s: %s' % (name, fn(*a, **kw))
fns[name] = handle
return fns
if __name__ == '__main__':
# On CPython 2.7.3:
#
# foo - quux: quux
# bar - quux: quux
# quux - quux: quux
fns = scan()
for name in ('foo', 'bar', 'quux'):
print '%s - %s' % (name, fns[name]())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment