Skip to content

Instantly share code, notes, and snippets.

@uucidl uucidl/insane.py
Created Mar 15, 2016

Embed
What would you like to do?
Something insane I did not know about python
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
>>>
@uucidl

This comment has been minimized.

Copy link
Owner Author

commented Mar 15, 2016

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

for a in [...]:
@sixohsix

This comment has been minimized.

Copy link

commented Mar 15, 2016

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.

@uucidl

This comment has been minimized.

Copy link
Owner Author

commented Mar 15, 2016

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
You can’t perform that action at this time.