Python helper function scope

Python helper function scope

In Python 3 you can do this by putting nonlocal x in the inner function. In Python 2 you cant do it.

However, what you can do instead is return the value from the helper function, and assign it where you call the helper function. Its a little hard to tell from your example, but Im assuming youre using it something like this:

def main():
    x = 10

    def helper(n):
        if (x > n):
            x -= n

    # do something that changes x
    helper(2)
    # now x has changed

Instead, do this:

def helper(x, n):
    if (x > n):
        return x - n
    else:
        return x

def main():
    x = 10

    # do something that changes x
    x = helper(x, 2)
    # now x has changed

The idea is to pass the helper function the values it needs, and have it return the resulting value, which you can then assign (or do what you like with) at the place where the helper is called. This also often makes the code easier to follow, as opposed to having the helper function directly modify variables in its caller. Also notice that here you can define helper outside main, creating a cleaner separation between the two, and also making helper available for use in other functions.

The problem is on the line: x -= n. Since you are doing an augmented assignment, python thinks (incorrectly) that x is a local variable. Unfortunately, x is a nonlocal variable. On python3.x, if you are OK with modifying x in the scope of main, then you can use the nonlocal keyword. However, Im guessing you dont want to modify x in mains scope. A cross-version trick is to get yourself a local variable with the same value as the non-local version:

def main():
    x = 10
    def helper(n):
        lx = x
        if x > n:
           lx -= n
        # etc., etc.

    helper(12)  # ...

If you really want to mutate x in the scope of main, you might want to consider a class (with helper a method on the class):

class Main(object):  # Main for lack of a better name...
    def __init__(self, x):
        self.x = x
    def helper(self, n):
        if self.x > n:
            self.x -= n

def main():
    x = Main(10)
    ...
    x.helper(12)
    ...

Python helper function scope

Leave a Reply

Your email address will not be published.