L
Licheng Fang
Specifically: a nested function cannot *RE-BIND* a variable of
an outer function.
Sorry to dig up this old thread, but I would like to know what's the
rationale is. Why can't a nested function rebind a variable of an
outer function?
One solution is the following, which I however do not see as very
clean or nice.-------8<-------8<-------8<-------8<-------
def test ():
count = [0]
def inc_count ():
count[0] += 1
inc_count ()
inc_count ()
print count[0]test ()
-------8<-------8<-------8<-------8<-------Now my question: Is there some way to achieve this with a nicer
syntax?
Depends on your tastes in syntax, e.g.:
def test():
class Bunch: pass
loc = Bunch()
loc.count = 0
def inc_count():
loc.count += 1
inc_count()
inc_count()
print loc.count
or:
def test():
test.count = 0
def inc_count():
test.count += 1
inc_count()
inc_count()
print test.count
and no doubt quite a few others.
I was trying to write a function that creates another function and
returns it when I came across this problem. These two solutions have a
difference:
def M():
M.c = 0
class Bunch:
pass
Bunch.c = 0
def f():
M.c += 1
Bunch.c += 1
print M.c, Bunch.c
return f
6 3
The created functions share their variables binded to the outer
function, but have their separate copies of variables bundled in a
class.
Is binding name to the function object a python way to use 'static'
variables? But how to initialize them?