5 ms·
Don't those languages typically have immutable variables so you would not be able to rebind a constant by accident?
by AlexandrB 6y ago
Don't those languages typically have immutable variables so you would not be able to rebind a constant by accident?
- deleted 6y ago[deleted]
- the_duke 6y agoThis is usually orthogonal to mutability. In other languages that support match, whether functional or not, you are not changing the value of the variable, but you are shadowing/rebinding the identifier inside the scope of the match clause.
- pansa2 6y agoPython `match` statements do not introduce a new scope. The second example does indeed change the value of `not_found`.
- deleted 6y ago[deleted]
- rwmj 6y agoOh dear, that is indeed very bad.
- mbo 6y agoWhat's the rationale for not introducing a new scope? The only clause I can find in the PEP is > A capture pattern always succeeds. It binds the subject value to the name using the scoping rules for name binding established for named expressions in PEP 572. (Summary: the name becomes a local variable in the closest containing function scope unless there's an applicable nonlocal or global statement.) This seems... incredibly bad.
- magnusmundus 6y agoIt's consistent with how scoping works in loops and `with` clauses. Agreed that it's more problematic here, though.
- 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 ago
- the_duke 6y agoThat's a very problematic design decision, imo...
- danielscrubs 6y agoDoesn’t other languages have block scope and shadowing is not an issue, but in Python it will reassign instead of shadowing? In my mind that is not well thought out.
- pfalcon 6y agoInterested in block-level scoping in Python? Please post on the python-ideas mailing list. Thanks.
- baby 6y agoIn Rust no