0

I try to create closure where in parent frame exists binding with name inner which only can be accessibly using methods I provide by return. Here is my code:

def test():
    inner = 'value'
    def get_inner():
        return inner
    def set_inner(v):
        inner = v
    return get_inner, set_inner


get, set = test()

set('hello world')

But, when I actually call set_inner() and in the body statement inner = v evaluated binding created in the local frame, but binding in the parent frame stays unchanged.

Here is how it looks:

enter image description here

as you can see new binding is created in the current frame of set_inner function, but I'd like to current the parent's binding.

I hope I made clear enough what I want to do.

Thank in advance.

EDITED:

Thank you to MartijnPieters, all I have to do is to place nonlocal statement:

def test():
    inner = 'value'
    def get_inner():
        return inner
    def set_inner(v):
        nonlocal inner
        inner = v
    return get_inner, set_inner

And now it changes binding in the parent frame

SuperManEver
  • 2,263
  • 6
  • 28
  • 36

0 Answers0