Created
March 15, 2016 08:45
-
-
Save uucidl/2a51ffcae6f72d77d4d0 to your computer and use it in GitHub Desktop.
Something insane I did not know about python
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
H:\temp>python | |
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 | |
Type "help", "copyright", "credits" or "license" for more information. | |
>>> a = 'hello' | |
>>> print a | |
hello | |
>>> words = [a for a in ['one', 'two', 'three']] | |
>>> print words | |
['one', 'two', 'three'] | |
>>> print a | |
three | |
>>> |
Yeah that's fun. Basically only def and class introduce scopes, nothing else (I think). The behavior above is sort of a feature since you can search for something in a loop and access it after.
And then you're like "what if I get to the end of a loop and nothing matched?" To counteract that for loops can have an "else" clause. :)
The 90's were weird.
Yeah this reminds me a lot of JavaScript. I thought python had more scopes.. I guess I'll liberally enclose most of my scopes in local functions from now on, unless it's at the expense of clarity
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I can understand mechanically why it does that, but that was really unexpected to me. I always assumed the list comprehension like feature would introduce a new scope where the variables would live.
It basically treats the [a for a in [...]] syntax just as sugar for a surrounding for loop, which trashes the other variable