tenwest tenwest - 2 months ago 12
Python Question

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):


  • Why can I see one but not the other?

  • Do I want to be prepending
    global
    to these variables I want to reassign?


Answer

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".