0

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.

2
  • 1
    python2 or python3? In python3 you can use nonlocal. Commented Aug 25, 2016 at 13:36
  • It is in Python 3 Commented Aug 25, 2016 at 13:37

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I'm using Python 3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.