mercredi 30 septembre 2015

Retrieve the names of (and default values of) the arguments accepted by a specified function

Say I have a function, foo which has some arguments...some positional and some keyword:

def foo(a, b=1.0, c=None):
    print a
    print c
    return 2 * b

Is there another function I can call with foo as an argument (or a method of foo which I can call) that will return to me a list of the positional arguments of foo as well as a list of tuples of the keyword arguments of foo along with their default values? Specifically, calling:

the_function_i_want(foo)

should return

(('a',), (('b', 1.0), ('c', None)))

Or something like that. To be clear I do not want a way to figure out what values were passed to foo one particular time that it was called. Instead I want information about the function signature of foo in a programatic way.

(The use case I have in mind is to automatically make a web form which will be able to submit appropriate data to serve as the arguments of a specified function. So that if I call web_form(foo) in the appropriate way, it will be able to render a web form with spaces for each of the arguments of foo with the default calling values pre-filled in an appropriate way.)





Aucun commentaire:

Enregistrer un commentaire