0

I've got a large function, inside which are nested a few functions, as follows:

def primary(input):

    def second():
        print "something"

    def third():
        treasure = "Success!"
        print treasure

The third() function defines the treasure variable and prints it. How should I change the scope of this variable so that I can print treasure from the interpreter without having to invoke any functions, but still allowing the functions to access/change it?

1
  • 1
    I strongly suggest you rethink the structure of your code, if this is what you need. Commented Jul 5, 2013 at 21:37

2 Answers 2

3

You would have to make it a global; local variables in functions are not accessible, nested or otherwise.

Just accessing treasure as a global works just fine:

treasure = "Success!"

def primary(input):
    def second():
        print "something"

    def third():
        print treasure

To change treasure within a function scope, declare it a global with the global keyword.

treasure = "Success!"

def primary(input):
    def second():
        print "something"

    def third():
        global treasure
        treasure = 'changed!'
        print treasure

    third()
Sign up to request clarification or add additional context in comments.

Comments

0

If the function third() add the keyword "global" in front of treasure. This allows other functions to use that variable.

There is another way of doing this, which is defining the var in at the start of the code, this looks much better, and is the way I learned how to do it.

treasure = "Success!"

def second():
    print "Something."

def third():
    print treasure

third()

Good luck.

1 Comment

You won't be able to modify the variable unless you use the global keyword: >>> treasure = "Success!" >>> def fourth(): ... treasure = "Island!" ... >>> fourth() >>> treasure 'Success!'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.