I got a piece of 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
defined in the outermost scop, I would prefer to have it only in outer
function. As I understand correctly, in Python3 this is done by nonlocal
. Is there a better method for what I want to have? I would prefer to declare and assign foo
in outer
and maybe to delcare 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 work, foo
seems to be searched in the outermost scope.