Calling a function with unknown arguments?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Mar 7 18:21:44 EST 2007
En Wed, 07 Mar 2007 19:55:08 -0300, Rob <crowell at mit.edu> escribió:
> I can get a list of a function's arguments.
>>>> def bob(a, b):
> ... return a+b
> ...
>>>> bob.func_code.co_varnames
> ('a', 'b')
>
> Let's say that I also have a dictionary of possible arguments for this
> function.
>>>> possible = {'a':10, 'b':5, 'c':-3}
>
> How do I proceed to call bob(a=10, b=5) with this information?
You're almost done. Notice that co_varnames includes local variables too;
only the first co_argcount are positional arguments.
If you only want to deal with positional arguments (no *args, no **kw):
py> def bob(a,b):
... c = a+b
... return c
...
py> bob.func_code.co_varnames
('a', 'b', 'c')
py> bob.func_code.co_argcount
2
py> args = dict((name, possible[name]) for name in
bob.func_code.co_varnames[:bo
b.func_code.co_argcount] if name in possible)
py> args
{'a': 10, 'b': 5}
py> bob(**args)
15
It can handle missing arguments (if they have a default value, of course):
py> def bob(a, k=3):
... return a+k
...
py> args = dict((name, possible[name]) for name in
bob.func_code.co_varnames[:bo
b.func_code.co_argcount] if name in possible)
py> args
{'a': 10}
py> bob(**args)
13
--
Gabriel Genellina
More information about the Python-list
mailing list