How to create a function at runtime with specified argument names?

Viewed 3859

Suppose I have this function:

def f(x,y):
   return x+y

If I use inspect.getargspec(f).args I get ['x','y'] as a result. Great.

Now suppose I want to create another function g(a,b) at runtime, where I don't know the argument names a and b until runtime:

def g(a,b):
   return f(a,b)

Is there a way to do this? Lambdas are almost right, except I can only assign argument names at compile time.

g = lambda *p: f(*p)

Somehow I want to create the function dynamically at run time based on a list L (for example L=['a','b']), so that inspect.getargspec(g).args == L).

4 Answers
Related