6 ms·
I think that feature has exactly zero chances of getting adopted, but that's probably one of my top Python annoyances too. If it's any consolation, the scope o
by arnsholt 7y ago
I think that feature has exactly zero chances of getting adopted, but that's probably one of my top Python annoyances too.
If it's any consolation, the scope of a variable isn't determined by heuristics, it's just that the rules are (IMO) kinda bad. Basically, if a variable is assigned (in addition to `=` and friends, `import`, `class` and `def` are also assignments in disguise) to in what Python calls a "block" (which is not like a C-style block; rather `class` body, `def` body, or top-level) it is considered to belong to that block (with the notable exception of the name for a caught exception in a `except Exception as e: ...`, see [1]). If you want it to refer to a variable outside the block, you need to use `global` or `nonlocal` as appropriate. The full gory details are in [2]
1: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement https://docs.python.org/3/reference/compound_stmts.html#the-...
2: https://docs.python.org/3/reference/executionmodel.html#naming-and-binding https://docs.python.org/3/reference/executionmodel.html#nami...
- eru 7y agoYes, I meant the rules are bad. I called them heuristics, because I assume they came up with the rules as a heuristic to what would be the most useful behaviour. Python didn't use to have lexical scoping, so the rules are retrofitting around that.
- arnsholt 7y agoYeah, it all seems a bit hacky. Especially the bit where a caught exception bound to a variable is cleared at the end of the `except` clause. I'm pretty sure it's because if you didn't you'd get a reference cycle (exception object -> stack trace -> function invocation record -> function locals -> exception object), which makes CPython's GC sad.