Created
March 1, 2013 15:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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