Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: How do I capture a variable declared in a non global ancestral outer scope?

Tags:

python

scope

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

like image 543
mark Avatar asked Apr 22 '12 18:04

mark


3 Answers

You can make x a function attribute:

def f():
    f.x = 0
    def g():
        h()
    def h():
        f.x += 1
        print(f.x)
    g()

Also, as of Python 3, you can use nonlocal keyword.

like image 65
ovgolovin Avatar answered Oct 21 '22 19:10

ovgolovin


If you're using Python 3, you use the nonlocal keyword. Put nonlocal x at the beginning of function h. If you're using Python 2.x, a workaround is making x a list with one element, so you can modify it:

def f():
    x = [0]
    def g():
        h()
    def h():
        x[0] += 1
        print x[0]
    g()

f()
like image 23
fferen Avatar answered Oct 21 '22 18:10

fferen


In Python 3 just use nonlocal:

def f():
    x = 0
    def g():
        h()
    def h():
        nonlocal x
        x += 1
        print(x)
    g()
f()
like image 6
Ashwini Chaudhary Avatar answered Oct 21 '22 18:10

Ashwini Chaudhary