123Bear Honey 123Bear Honey - 3 months ago 12
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
print(globvar)
add_one_to_globvar()
go_to_next_function()


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

Answer

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]
    add_one()
go_to_next_function()
Comments