inspecting a callable for the arguments it accepts

Chris Angelico rosuav at gmail.com
Wed Nov 15 01:15:16 EST 2017


On Wed, Nov 15, 2017 at 4:34 PM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Chris Angelico wrote:
>
>>>>> wants_one_arg.__code__.co_argcount
>>
>>
>> 1
>>
>>>>> wants_one_arg.__code__.co_varnames
>>
>>
>> ('x',)
>
>
> That will give you some idea, but it's not foolproof -- e.g.
> if the function has * or ** arguments, it's impossible to tell
> in general how many arguments it accepts without studying the
> code (and maybe not even then -- halting problem, etc.)
>
> Some of the co_flags seem to indicate presence of * and **:
>
> 0x04 - has *args
> 0x08 - has **kwds
>
> In Py3 there is also co_kwonlyargcount.

Yep. Browsing __code__'s attributes was the stepping-stone to the
actual way of doing it: the inspect module. But I figured it's better
to look at those attributes briefly rather than say "here's the
inspect module, it uses magic".

ChrisA



More information about the Python-list mailing list