Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change nesting function's variable in the nested function

I'd like to have variable defined in the nesting function to be altered in the nested function, something like

def nesting():
    count = 0
    def nested():
        count += 1

    for i in range(10):
        nested()
    print count

When nesting function is called, I wish it prints 10, but it raises UnboundLocalError. The key word global may resolve this. But as the variable count is only used in the scope of nesting function, I expect not to declare it global. What is the good way to do this?

like image 371
bxx Avatar asked Jun 01 '11 09:06

bxx


1 Answers

In Python 3.x, you can use the nonlocal declaration (in nested) to tell Python you mean to assign to the count variable in nesting.

In Python 2.x, you simply can't assign to count in nesting from nested. However, you can work around it by not assigning to the variable itself, but using a mutable container:

def nesting():
    count = [0]
    def nested():
        count[0] += 1

    for i in range(10):
        nested()
    print count[0]

Although for non-trivial cases, the usual Python approach is to wrap the data and functionality in a class, rather than using closures.

like image 169
Thomas Wouters Avatar answered Oct 21 '22 01:10

Thomas Wouters