Is there something like "non-local" in Python <3?
I have a code like this:
foo = None def outer(): global foo foo = 0 def make_id(): global foo foo += 1 return foo id1 = make_id() # id = 1 id2 = make_id() # id = 2 id3 = make_id() # ...
I find it ugly to have foo
it defined in an external scop, I would rather only use it in outer
. As I understand it correctly, in Python3 this is done using nonlocal
. Is there a better way for what I want to have? I'd rather declare and assign foo
to, outer
and perhaps consider it global
in inner
:
def outer(): foo = 0 def make_id(): global foo foo += 1 # (A) return foo id1 = make_id() # id = 1 id2 = make_id() # id = 2 id3 = make_id() # ...
(A) does not seem to work foo
in the outermost area.
source share
I am using 1-item lists for this purpose:
def outer(): foo = [0] def make_id(): r = foo[0] foo[0] += 1 return r return make_id make_id = outer() id1 = make_id() id2 = make_id() ...
This is the same as when used, nonlocal
due to the slightly more cumbersome syntax ( foo[0]
instead of foo
).
source share