Usage of types.FunctionType with closure option

Viewed 176

I am exploring dynamic creation of function objects by FunctionType (for learning purposes) and can't understand how to use a closure parameter.

From help(types.FunctionType):

function(code, globals[, name[, argdefs[, closure]]])

The optional closure tuple supplies the bindings for free variables.

A simple expression works:

def foo():
    code = compile("print(3 + 2)", filename='FunctionType_test', mode='eval')
    new_func = types.FunctionType(code, globals(), "generated_function")
    return new_func

foo()()

How can I bind a variable from outer scope to a new function object?

def foo(foo_var):
    code = compile("print(foo_var + 2)", filename='FunctionType_test', mode='eval')
    new_func = types.FunctionType(code, globals(), "generated_function")
    return new_func

foo(3)()

I want to achieve the same behaviour, but by FunctionType:

def foo(foo_var):
    def bar():
        print(foo_var + 2)

    return bar

foo(3)()
0 Answers
Related