123Bear Honey 123Bear Honey - 1 year ago 55
Python Question

Variable defined in a function, needed within a function within this function - Python

I need to define a variable within a function and use it in a function that is within the original function. For example,

def go_to_next_function():
globvar = 0
def add_one_to_globvar():
global globvar
for i in range(10):
globvar += 1

Now I know if
is defined outside all of the functions then it would work, but I want it to be defined inside the
function. Any ideas? Thanks.

Answer Source

If you are using python3.x, you can use the nonlocal keyword rather than global and your function should work.

If you're on python2.x, you're stuck with old hacks like putting the value in a container and mutating that. It's an ugly hack (which is why nonlocal was added in the first place):

def go_to_next_function():
    closure_var = [0]
    def add_one():
        closure_var[0] += 1
        print closure_var[0]