Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I'm not sure if this is needed for variables that are only read

It’s not needed. In fact, you should leave it out for read-only variables. That’s standard practice - if you use `nonlocal` people reading the code will expect to see writes to the variables.



> That’s standard practice - if you use `nonlocal` people reading the code will expect to see writes to the variables.

Since when? I was under the impression Python virtually doesn't have lexical scoping at all and that's why `nonlocal` exists. I mean hell, in CPython you can literally access and modify the local variables of your caller (and everything else up the call stack too). I never associated `nonlocal` at all with specifically writes. Just access in general.


> I was under the impression Python virtually doesn't have lexical scoping at all and that's why `nonlocal` exists

Python has had lexical scoping since version 2.2. PEP 227 [0] "describes the addition of statically nested scoping (lexical scoping)" - allowing access to (but not assignment to) names in outer scopes.

`nonlocal` was introduced later, in Python 3.0 [1], specifically to allow assignment to names in outer scopes.

[0] https://peps.python.org/pep-0227/

[1] https://peps.python.org/pep-3104/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: