Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Modify bound variables of a closure in Python

Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.

def foo():
    var_a = 2
    var_b = 3

    def _closure(x):
        return var_a + var_b + x

    return _closure


localClosure = foo()

# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6

# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?

# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4

Answer*

Cancel
3
  • i would too, it's certainly better than the other way. i just meant that by default it should be nonlocal Commented Dec 30, 2008 at 22:16
  • 4
    Doh! I meant to say I wouldn't. It still looks weird and hacky to me. The whole bit about the optional parameter to change value. Whole thing should be a class. But anyway, I digress. Commented Dec 30, 2008 at 22:35
  • for future readers, this became possible with no code changes required in 2017 with Python 3.7.0 alpha 1, see my post for details Commented Nov 30, 2022 at 3:41