Knowing the signature of a function

  • Thread starter =?ISO-8859-1?Q?Xavier_D=E9coret?=
  • Start date

?

=?ISO-8859-1?Q?Xavier_D=E9coret?=

Hello,

I have the following code:

def foo(x,y):
pass

How can I query the function object foo to know the number of parameters
it expects. I can find it is a function using callable(f), I can find
some information (listed by dir(foo)) such as the name of the
function,etc.. but nowhere I can find the number of arguments.

I would like to know wether the function expects one or zero arguments.
 
Ad

Advertisements

K

Kent Johnson

Xavier said:
Hello,

I have the following code:

def foo(x,y):
pass

How can I query the function object foo to know the number of parameters
it expects. I can find it is a function using callable(f), I can find
some information (listed by dir(foo)) such as the name of the
function,etc.. but nowhere I can find the number of arguments.

I would like to know wether the function expects one or zero arguments.

foo.func_code.co_argcount gives the count of named args. len(foo.func_code.co_varnames) gives the total number of arguments including *args and **kwds args. inspect.getargspec() might also be helpful.

Kent
 
?

=?ISO-8859-1?Q?Xavier_D=E9coret?=

Kent Johnson a écrit :
foo.func_code.co_argcount gives the count of named args.
len(foo.func_code.co_varnames) gives the total number of arguments
including *args and **kwds args. inspect.getargspec() might also be
helpful.

Kent

Thanks.

Now I have the following issue: what if foo is not a function but a
callable? inspect.getargspec raises an exception.

I have to do something like:


import inspect

def countargs(f):
if callable(f):
if inspect.isfunction(f): return len(inspect.getargspec(f)[0])
return len(inspect.getargspec(f.__call__)[0])-1
raise ValueError

class foo:
def __call__(self,a,b):
pass

def bar(x):
pass


print countargs(foo)
print countargs(bar)



Is there any better way?
 
Ad

Advertisements

S

Steven D'Aprano

foo.func_code.co_argcount gives the count of named args.
len(foo.func_code.co_varnames) gives the total number of arguments
including *args and **kwds args. inspect.getargspec() might also be
helpful.

You guys are amazing, have you been spying on me? :) I was just about to
write in with the same question. Thanks for answering before I asked.
 

Top