Function argument conformity check

Cédric Lucantis omer at no-log.org
Wed Jun 18 15:13:15 EDT 2008


Hi,

Le Wednesday 18 June 2008 20:19:12 dlists.cad at gmail.com, vous avez écrit :
> Hi. I am looking for a way to check if some given set of (*args,
> **kwds) conforms to the argument specification of a given function,
> without calling that function.
>
> For example, given the function foo:
> def foo(a, b, c): pass
>
> and some tuple args and some dict kwds, is there a way to tell if i
> _could_ call foo(*args, **kwds) without getting an exception for those
> arguments? I am hoping there is a way to do this without actually
> writing out the argument logic python uses.
>

Each function object is associated to a code object which you can get with 
foo.func_code. Two of this object's attributes will help you: co_argcount and 
co_varnames. The first is the number of arguments of the function, and the 
second a list of all the local variables names, including the arguments 
(which are always the first items of the list). When some arguments have 
default values, they are stored in foo.func_defaults (and these arguments are 
always after non-default args in the co_argnames list). 

Finally, it seems that some flags are set in code.co_flags if the function 
accepts varargs like *args, **kwargs, but I don't know where these are 
defined.

Note that I never found any doc about that and merely guessed it by playing 
with func objects, so consider all this possibly wrong or subject to change.

-- 
Cédric Lucantis



More information about the Python-list mailing list