Faller
Faller

Reputation: 1698

python - Changing a variable with a nested function

Excuse me for being new to python. I feel as if this should be possible, but I have looked all over in this site (among others). I can't seem to directly change a variable in a function with a nested function. I've tried

global 

to no avail. I could reassign it to get around this but it causes issues later.
Example:

def Grrr():
    a = 10
    def nested(c):
        b = 5
        c -= b
    nested(a)
    return a

I am trying to stay away from

def Grrr():
    a = 10
    def nested(c):
        b = 5
        c -= b
    a = nested(a)
    return a

If that is truly the best way, then I'll use it I guess. I just figured there were people here far better than I.

Upvotes: 2

Views: 104

Answers (1)

icktoofay
icktoofay

Reputation: 129001

You could avoid using an argument and instead use nonlocal:

def Grrr():
    a = 10
    def nested():
        nonlocal a
        b = 5
        a -= b
    nested()
    return a

If you want to pass in a variable to change, though, it can't be done; Python doesn't have references in the C++ sense.

† without some horrible hackery

Upvotes: 4

Related Questions