tenwest
tenwest

Reputation: 2317

Accessing global function's variables in a local function

Here's my test script:

def main(): #global
    n = 1
    z = None

    def addone():  #local
        if not z:
            n = n+1
    addone()
    print n

main()

I step into the addone() function once it hits the calling line. At this point I can only see the variable z, but cannot see n.

Now, if n is referenced before assignment, shouldn't z be too?

Similarly, if I change n=n+1 to z='hi', I can no longer see z! This is contrary to all my previous beliefs about local/global functions! The more you know, the more you know you don't know about Python.

Question(s):

Upvotes: 1

Views: 119

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881775

The best solution is to upgrade to Python 3 and use in the inner function nonlocal n. The second-best, if you absolutely have to stick with Python 2:

def main(): #global
    n = [1]
    z = None

    def addone():  #local
        if not z:
            n[0] += 1
    addone()
    print n[0]

main()

As usual, "there is no problem in computer science that cannot be solved with an extra level of indirection". By making n a list (and always using and assigning n[0]) you are in a sense introducing exactly that life-saving "extra level of indirection".

Upvotes: 1

tenwest
tenwest

Reputation: 2317

Okay, after some testing, I realised that it all has to do with the reassignment of variables.

for example:

def main(): #global
    n = 1
    z = None

    def addone():  #local
        if not z:
            x = n+1
    addone()
    print n

main()

Now shows both n and z when I am inside the addone() function. This is because I am no longer trying to reassign n, makes sense to me so as to protect global variables from manipulation if one so happens to use similar names in local functions.

Upvotes: 0

Related Questions