4 ms·
> And you can't do something like this in a clean way: That's what nonlocal is for: https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statemen
by viraptor 9y ago
> And you can't do something like this in a clean way:
That's what nonlocal is for: https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement https://docs.python.org/3/reference/simple_stmts.html#the-no...
Just stick "nonlocal counter" in your function and it works.
- amelius 9y agoTrue. But nonlocal is relatively new. Also nonlocal implies that other variables are local, which is not true. E.g., the following works without "nonlocal" keyword: counter = [0] def add(n): counter[0] += n add(1) add(2) (This used to be my workaround.)
- viraptor 9y agoYup, relatively new. Only around since python 3.0, for the last 12 years ;-)
- camel_Snake 9y agononlocal implies that you are reassigning a variable outside of the local scope. Your example works because you are mutating an existing object, not reassigning a new one. It's a disingenuous comparison IMO.