Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a variable inside a method with another method inside it

Tags:

The following code raises an UnboundLocalError:

def foo():     i = 0     def incr():         i += 1     incr()     print(i)  foo() 

Is there a way to accomplish this?

like image 689
shooqie Avatar asked Dec 23 '15 08:12

shooqie


1 Answers

Use nonlocal statement

def foo():     i = 0     def incr():         nonlocal i         i += 1     incr()     print(i)  foo() 

For more information on this new statement added in python 3.x, go to https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement

like image 64
piglei Avatar answered Sep 18 '22 23:09

piglei