Achim
Achim

Reputation: 15702

Python code generation: Create functions with varying but known number of parameters of the fly

Doing some metaprogramming in Python, I have to create a function on the fly. My problem is that the number of parameters is not determined until generating the code. So different generated functions will have different parameters with different names. But when the function is generated, all information is available and I do NOT want to use **args! Here's an example:

# information collected by my codgen process
arg_names = ['param_a','param_b','param_c']
some_callable = ClassDeterminedWhileGeneratingCode

What I would like to generate, is a function like this one, which will be added to a class:

def my_fkt(self,param_a,param_b,param_c):
    instance = some_callable(param_a=param_a,param_b=param_b,param_c=param_c)
    self.do_something(instance)
    return instance.generate_result()

I'm quite used to generate functions using higher order functions, but that does not help if the number of parameters is not fixed. I'm quite sure, that I have somewhere seen code creating functions using type.FunctionType. But I was not able to find any documentation about that.

Upvotes: 0

Views: 272

Answers (2)

westandskif
westandskif

Reputation: 982

Try convtools library, it supports input_args and a lot of other stuff, which is all about generating ad hoc code.

Upvotes: 0

rocksportrocker
rocksportrocker

Reputation: 7419

Have a look at,

http://snipplr.com/view/17819/

if you want to manipulate the argument names, you should replace "y.func_code.co_varnames" by a tuple with the given names.

Cheers, Uwe

Upvotes: 1

Related Questions