Created
April 15, 2020 10:59
-
-
Save koirikivi/72727668e3ed10d10aa5765aea4cb863 to your computer and use it in GitHub Desktop.
Replace closure variables in Python (stupid)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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