5 ms·
I'd really like a way to refer to a variable in a outer scope (like global... but not just for global variables).
by edflsafoiewq 7y ago
I'd really like a way to refer to a variable in a outer scope (like global... but not just for global variables).
- paultudorjones 7y agoThat would be “nonlocal”. https://www.programiz.com/python-programming/global-local-nonlocal-variables https://www.programiz.com/python-programming/global-local-no...
- eru 7y agoIn the same vein, they could add syntax to distinguish introducing a variable from setting the value of an existing variable. Python's heuristics for that are pretty annoying.
- arnsholt 7y agoI 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.
- alanfranz 7y ago... and what prevents you from doing that? You mean you'd want to reassign them?