Skip to content

Instantly share code, notes, and snippets.

@mattjj
Last active November 22, 2017 19:31
Show Gist options
  • Save mattjj/0aaf23e7b475036f41d9051f0ff33cec to your computer and use it in GitHub Desktop.
Save mattjj/0aaf23e7b475036f41d9051f0ff33cec to your computer and use it in GitHub Desktop.
import types
def closure_conversion(f):
code, globs, freevars = f.func_code, f.func_globals, f.func_code.co_freevars
env = dict(zip(freevars, (c.cell_contents for c in f.func_closure)))
make_cell = lambda val: (lambda: val).func_closure[0] # different in PY3
def f_maker(env):
closure = tuple(make_cell(env[name]) for name in freevars)
return types.FunctionType(code, globs, closure=closure)
return f_maker, env
f = (lambda x: lambda y: x + y)(2)
print f(2)
f_, env = closure_conversion(f)
print env
print f_({'x': 3})(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment