Skip to content

Instantly share code, notes, and snippets.

@koirikivi
Created April 15, 2020 10:59
Show Gist options
  • Save koirikivi/72727668e3ed10d10aa5765aea4cb863 to your computer and use it in GitHub Desktop.
Save koirikivi/72727668e3ed10d10aa5765aea4cb863 to your computer and use it in GitHub Desktop.
Replace closure variables in Python (stupid)
def foo():
x = 42
def f():
return x
return f
f = foo()
f() # 42
def replace_closure_variables(func, **kwargs):
variable_names = func.__code__.co_freevars
cells = func.__closure__
for k, v in kwargs.items():
pos = variable_names.index(k)
cells[pos].cell_contents = v
replace_closure_variables(f, x=200)
f() # 200
replace_closure_variables(f, x=123)
f() # 123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment