Given:
def f():
x = 0
def g():
h()
def h():
x += 1
print(x)
g()
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in f
File "<stdin>", line 4, in g
File "<stdin>", line 6, in h
UnboundLocalError: local variable 'x' referenced before assignment
>>>
How can I make h
see the x
variable?
Thanks.
EDIT
Should have mentioned it earlier, I am using Python 2.7.3
You can make
x
a function attribute:Also, as of Python 3, you can use
nonlocal
keyword.In Python 3 just use
nonlocal
:Easiest is to use a dict or empty class, e.g.:
Although many good solutions were already provided, they have corner cases:
f
is redefined and later called by referenceIf you're using Python 3, you use the
nonlocal
keyword. Putnonlocal x
at the beginning of functionh
. If you're using Python 2.x, a workaround is makingx
a list with one element, so you can modify it:Can't we put
x
as function arguments as workaround