En Wed, 07 Mar 2007 19:55:08 -0300, Rob <cr*****@mit.eduescribió:
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):
pydef bob(a,b):
.... c = a+b
.... return c
....
pybob.func_code.co_varnames
('a', 'b', 'c')
pybob.func_code.co_argcount
2
pyargs = dict((name, possible[name]) for name in
bob.func_code.co_varnames[:bo
b.func_code.co_argcount] if name in possible)
pyargs
{'a': 10, 'b': 5}
pybob(**args)
15
It can handle missing arguments (if they have a default value, of course):
pydef bob(a, k=3):
.... return a+k
....
pyargs = dict((name, possible[name]) for name in
bob.func_code.co_varnames[:bo
b.func_code.co_argcount] if name in possible)
pyargs
{'a': 10}
pybob(**args)
13
--
Gabriel Genellina