Skip to content

Instantly share code, notes, and snippets.

@kisielk
Created May 8, 2012 18:30
Show Gist options
  • Select an option

  • Save kisielk/2638271 to your computer and use it in GitHub Desktop.

Select an option

Save kisielk/2638271 to your computer and use it in GitHub Desktop.
Python scoping rules can sometimes result in code working purely by accident.
def omg():
def inner(foo):
# Works fine, purely by accident...
return f
# ...because the list comprehension leaks its variable in to the outer scope
return [inner(f) for f in range(5)]
def broken():
def inner(foo):
# Raises a NameError...
return f
# ...because generators *don't* leak the iteration variable in to the outer scope
return list(inner(f) for f in range(5))
# In my real code I meant to use 'foo' inside the 'inner' function but forgot to rename it from 'f'
# when copying some code around. I never noticed the mistake because the code still worked, and tests passed.
if __name__ == "__main__":
print omg()
print broken()
@sigmavirus24

Copy link
Copy Markdown

It's fixed in python 3, but you're right, it does seem to leak in python 2.x. Very interesting bug...

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