1

I am trying to use compile to runtime generate a Python function accepting arguments as follows.

import types
import ast

code = compile("def add(a, b): return a + b", '<string>', 'exec')
fn = types.FunctionType(code, {}, name="add")
print(fn(4, 2))

But it fails with

TypeError: <module>() takes 0 positional arguments but 2 were given

Is there anyway to compile a function accepting arguments using this way or is there any other way to do that?