6 ms·
"Introducing a new scope" is not a concept that exists in Python, you only have function scope and module scope.
by pdw 6y ago
"Introducing a new scope" is not a concept that exists in Python, you only have function scope and module scope.
- pansa2 6y agoThere are some exceptions to this - for example, the iteration variable(s) in a list comprehension are only in scope within the comprehension.
- pdw 6y agoThanks, I didn't realize that. That makes their choice really baffling.
- _nosewings_ 6y agoThe explanation is that (in Python 3) list comprehensions are really just syntactic sugar for generator expressions. In Python, "scope" is really a synonym for "dictionary attached to some object", so generators can have local variables (since they have their own internal scope), but purely syntactic constructs cannot.
- amirkdv 6y agoWorth noting that this was _fixed_ in Python 3. In Python 2.7 you get this: >>> my_list = [x for x in 'hello'] >>> x 'o'
- remram 6y agoand class scope
- CogitoCogito 6y agoHaving only function, module, class, generator, etc. scope in Python before this PEP might have made sense, but they really should have added pattern matching scope to keep things sane here.