2

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.

1 Answer 1

4

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

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

4 Comments

I would like to see this horrible hackery. Are you just talking about constructing a wrapper object like [thing] and passing that around instead of thing (much like Python's closure implementation uses cell objects), or is there actually a way to figure out which variable an argument came from and mess with the stack to alter its contents?
A true thing of beauty and exactly what I was looking for. Thank you.
@user2357112: I was thinking of walking up the stack until you find the function, looking at its the AST of whatever expression was currently executing in the stack frame to find what variable it was called with, and modifying the local variables dict of that stack frame.
@user2357112: I started writing a proof of concept. It turns out that, while possible, it's very difficult: I decided to simplify the problem to functions called with a single argument in the most obvious way. Everything works until the point where it modifies the local variables of that frame. It turns out that Python won't read back any changes from the dictionary. The real local variables are tucked away in a place that's difficult to access with Python. I started writing some ctypes code to get at it anyway, but there's some edge cases and lots depends on how Python was compiled.

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.