Drake Guan
Drake Guan

Reputation: 15122

Is it possible to generate a Python function with arguments in runtime?

Say,

I have a python function as following:

def ooxx(**kwargs):
    doSomething()
    for something in cool:
        yield something

I would like to provide another function with named arguments for hints as following:

def asdf(arg1, arg2, arg3=1):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    kwargs = dict((key, values[key]) for key in args) # convert args list into dictionary form
    return list(ooxx(**kwargs))

Is it possible to have some sort of methods to generate automatically the function "asdf"? I have lots of dynamic generated ooxx functions and I would like to have corresponding asdf functions with customized named arguments. Not sure if this is the correct requirement or right way to coding :p

Upvotes: 1

Views: 619

Answers (1)

Jochen Ritzel
Jochen Ritzel

Reputation: 107628

Your descriptions doesn't make such sense to me: You wrote a really verbose function that does this:

def asdf(arg1, arg2, arg3=1):
    return list(ooxx(**locals()))

but you want to inspect the ooxx and somehow make up appropriate names for asdfs arguments? That is impossible, there is no information about this on ooxx.

If you actually have a signature and want to create a function from it you would have to resort to eval or generate function definitions to a Python file and import it.

There is also the decorator module. You can create a function with it like this:

import decorator
asdf = decorator.FunctionMaker.create(
                'asdf(arg1, arg2, arg3)', # signature
                'return ooxx(**locals())', # function body
                {'ooxx' : ooxx}, # context for the function
                ('arg3', 1)) # default arguments

Upvotes: 4

Related Questions