Skip to content Skip to sidebar Skip to footer

How To Call A Compiled Function Body?

When I get hold of a code object (via internals like .func_code or __code__ in Python 3), is there any way of calling this piece of code? Simply calling it does not work: def f():

Solution 1:

One can eval() or exec them.

If they have free variables (e. g. for the code of nested functions whose outer function has local variables defined before the nested function), this is not directly possible (eval or exec raise a TypeError in this case).

Also, passing arguments to the code is not directly possible.

But one can create a wrapping function for the given code on-the-fly. This function can normally be called (using f(…)), passing arguments in the usual way. This is done using types.FunctionType. To achieve references to free variables, one must use a trick in order to get the correct data type as Python expects it. See the code below for an example:

deff(v1=1):
  v2 = 2defg(v3=4):
    return v1 + v2 + v3 + 8return g() + 16deffreeVar(val):
  defnested():
    return val
  return nested.__closure__[0]

defnested(outer, innerName, **freeVars):
  ifisinstance(outer, (types.FunctionType, types.MethodType)):
    outer = outer.func_code
  for const in outer.co_consts:
    ifisinstance(const, types.CodeType) and const.co_name == innerName:
      return types.FunctionType(const, globals(), None, None, tuple(
          freeVar(freeVars[name]) for name in const.co_freevars))

nestedG = nested(f, 'g', v1=1, v2=2)
print nestedG(4)  # will print 15

Post a Comment for "How To Call A Compiled Function Body?"