Created
May 8, 2012 18:30
-
-
Save kisielk/2638271 to your computer and use it in GitHub Desktop.
Python scoping rules can sometimes result in code working purely by accident.
This file contains hidden or 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
| 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's fixed in python 3, but you're right, it does seem to leak in python 2.x. Very interesting bug...