4 ms·
Regarding globals, defaulting to local scope is a thorny design choice. Try this in python: def make_counter(): def incr(x): total = to
by bhk 4y ago
Regarding globals, defaulting to local scope is a thorny design choice. Try this in python:
def make_counter():
def incr(x):
total = total + x
return total
total = 0
return incr
I think Lua would be a better language if they were to eliminate global variables entirely, and flag as a load-time error any undeclared variable that is not present in the environment supplied to `load` or `loadfile`.
Setting __newindex on the global table to throw errors is a not-too-bad solution, but these will be run-time errors, so to catch them all you need good code coverage (yes, you want that anway) and uncouth third-party libraries can trigger those errors.
- afiori 4y agoI personally like the php `use (...)` approach https://www.php.net/manual/en/functions.anonymous.php https://www.php.net/manual/en/functions.anonymous.php
- edflsafoiewq 4y agoTotal occurrences of nonlocal in Python are tiny. Typoing variables is a constant fact of life.
- kzrdude 4y agoPython would be a better language if it had Lua's local. Because Python would have true lexically scoped variables that way, instead of the current system.
- intrepidhero 4y agoEDIT: re-reading your comment I think I see now you were agreeing with me. :-) Leaving this here as elucidation. That python code throws UnboundLocalError, which seems like what it should do to me. If you move total = 0 to before def incr(x): then incr closes over the local total variable. Every call to make_counter returns a new counter with its own state. The equivalent Lua defines total as a global (whether total = 0 is above or below). Multiple instances of incr are all changing the same global variable. That doesn't like the intended behavior.
- intrepidhero 4y agoWhoops, actually the python version only works if you move total AND add a nonlocal keyword. https://docs.python.org/3/reference/simple_stmts.html?highlight=nonlocal#nonlocal https://docs.python.org/3/reference/simple_stmts.html?highli...
- bhk 4y agoThe existence of `nonlocal` is an indictment of the local-by-default design. (Parenthetically, for completeness, I should note that this is a problem only when the language supports mutable variables or, more precisely, mutable captures or "upvalues", which I think are also a bad idea, but that's another bag of worms for another day.)