Function argument conformity check

dlists.cad at gmail.com dlists.cad at gmail.com
Wed Jun 18 21:41:44 CEST 2008


On Jun 18, 3:13 pm, Cédric Lucantis <o... at no-log.org> wrote:
> Hi,
>
> Le Wednesday 18 June 2008 20:19:12 dlists.... 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

I am aware of these attributes, although you can get them all in a
more organized form using the getfullargspec function in the inspect
module from the standard library.

The problem is that using these attributes, I would essentially have
to re-write the logic python uses when calling a function with a given
set of arguments. I was hoping there is a way to get at that logic
without rewriting it.



More information about the Python-list mailing list