0

I can use inspect.getargspec to get the parameter names of any function, including bound methods:

>>> import inspect
>>> class C(object):
...     def f(self, a, b):
...             pass
...
>>> c = C()
>>> inspect.getargspec(c.f)
ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=None)
>>>

However, getargspec includes self in the argument list.

Is there a universal way to get the parameter list of any function (and preferably, any callable at all), excluding self if it's a method?

EDIT: Please note, I would like a solution which would on both Python 2 and 3.

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131

1 Answers1

0

inspect.signature excludes the first argument of methods:

>>> from inspect import signature
>>> list(signature(c.f).parameters)
['a', 'b']

You could also delete the first element of args manually:

from inspect import ismethod, getargspec

def exclude_self(func):
    args = getargspec(func)
    if ismethod(func):
        args[0].pop(0)
    return args

exclude_self(c.f) # ArgSpec(args=['a', 'b'], ...)
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • Is there a solution which works both on Python 2 and 3? – Aviv Cohn Jan 16 '16 at 17:45
  • @AvivCohn: I just posted it. Note that `getargspec` is gone in Python 3.6. – vaultah Jan 16 '16 at 17:45
  • To support both Python 2 and 3, I think I'll combine both yours and @Flippy's suggestions: get the arguments using `f.func_code.co_varnames[:f.func_code.co_argcount]` if it's a function or `f.func_code.co_varnames[1:f.func_code.co_argcount]` if it's a method. Thanks – Aviv Cohn Jan 16 '16 at 18:01
  • @AvivCohn: what's stopping you from using the second solution from my answer? – vaultah Jan 16 '16 at 18:06