Skip to content

Instantly share code, notes, and snippets.

@infotroph
Created September 14, 2015 22:35
Show Gist options
  • Save infotroph/544c3ba3894cef91c0b4 to your computer and use it in GitHub Desktop.
Save infotroph/544c3ba3894cef91c0b4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
lst = [{'one':1,'two':2,'three':3}, {'one':100,'two':200,'three':300}]
def wrapper(x, fun):
return fun(x)
def this_works():
def local_inner(d):
return d[key]
key='one'
return [wrapper(d, local_inner) for d in lst]
print(this_works())
# [1, 100]
def external_inner(d):
return d[key]
def this_fails():
key = 'one'
return [wrapper(d, external_inner) for d in lst]
print(this_fails())
# Traceback (most recent call last):
# File "inner.py", line 24, in <module>
# print(this_fails())
# File "inner.py", line 22, in this_fails
# return [wrapper(d, external_inner) for d in lst]
# File "inner.py", line 22, in <listcomp>
# return [wrapper(d, external_inner) for d in lst]
# File "inner.py", line 6, in wrapper
# return fun(x)
# File "inner.py", line 18, in external_inner
# return d[key]
# NameError: name 'key' is not defined
@infotroph
Copy link
Author

Questions:

  1. Why isn't key in scope in the second example? For extra credit, what do I misunderstand that's making this surprising to me?
  2. How to fix it, short of passing key as a parameter (= modifying the wrapper function to accept more parameters, which may be a hassle)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment