How to find argument list of a callable?

D

David Eppstein

Suppose I have a callable object x, and suppose for simplicity that it
doesn't take any *- or **-arguments. How can I get a list of the number
and names of the arguments of x?

If x is a function, then apparently this list is in
x.func_code.co_varnames[:x.func_code.co_argcount]. If x is an old-style
class, it's in
x.__init__.func_code.co_varnames[1:x.__init__.func_code.co_argcount].
If x is an object with a call method, it's in
x.__call__.func_code.co_varnames[1:x.__call__.func_code.co_argcount].
If x is a bound method or a new-style class, I have no idea how to find
the argument names, and for all I know there are several other classes
of callable that I haven't even thought of.

So far the only cases I actually need are functions and old-style
classes, so I have working code, but I have the nagging suspicion that
there's a cleaner way of doing this that I'm missing.

For that matter, is there a good way of testing whether x is an
old-style class? inspect.isclass(x) and not isinstance(x,type) seems to
work but feels kind of clunky.
 
A

Andrew Dalke

David Eppstein:
Suppose I have a callable object x, and suppose for simplicity that it
doesn't take any *- or **-arguments. How can I get a list of the number
and names of the arguments of x?

Take a look at the 'inspect' module.
.... pass
....
inspect.getargspec(spam) (['x', 'y', 'z'], None, None, (4,))

def eggs(a, b, *c, **d):
.... pass
....
inspect.getargspec(eggs) (['a', 'b'], 'c', 'd', None)

Andrew
(e-mail address removed)
 
G

Gonçalo Rodrigues

For that matter, is there a good way of testing whether x is an
old-style class? inspect.isclass(x) and not isinstance(x,type) seems to
work but feels kind of clunky.

Don't know if it's enough for what you have in mind but old-style
classes don't have a __class__ attribute.
.... pass
.... Traceback (most recent call last):
.... pass
....
With my best regards,
G. Rodrigues
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top