18

To keep a couple modules I'm building in Python a bit consistent I want to do some automated code checking. For this I want to check the modules for their functions and the arguments the functions take. I can use hasattr() to check whether the module actually contains the expected functions. So far so good.

I now want to see which arguments the functions take. It would be enough to simply see the variable names. I have no idea how I would be able to do this though. Does anybody know how I can get the names of the arguments a function takes?

tshepang
  • 12,111
  • 21
  • 91
  • 136
kramer65
  • 50,427
  • 120
  • 308
  • 488
  • 1
    Look at [`inspect.getargspec`](https://docs.python.org/2/library/inspect.html#inspect.getargspec) and other functions in that module. – BrenBarn Apr 22 '14 at 19:41
  • 1
    I understand that there's a duplicate of this, but I simply didn't find it because I didn't know what a signature is. I can imagine there are more people with the same deficit, so I would propose to leave this question open for future readers. – kramer65 Apr 22 '14 at 19:52
  • 1
    @kramer65: duplicate questions are not deleted for the reasons you mentioned, basically the duplicate questions are kept to become link baits for search engine for people that uses different search keywords than the canonical answer. – Lie Ryan Apr 22 '14 at 22:11

1 Answers1

36

You can use inspect.getargspec() to see what arguments are accepted, and any default values for keyword arguments.

Demo:

>>> def foo(bar, baz, spam='eggs', **kw): pass
... 
>>> import inspect
>>> inspect.getargspec(foo)
ArgSpec(args=['bar', 'baz', 'spam'], varargs=None, keywords='kw', defaults=('eggs',))
>>> inspect.getargspec(foo).args
['bar', 'baz', 'spam']

In Python 3, you want to use inspect.getfullargspec() as this method supports new Python 3 function argument features:

>>> def foo(bar: str, baz: list, spam: str = 'eggs', *, monty: str = 'python', **kw) -> None: pass
... 
>>> import inspect
>>> inspect.getfullargspec(foo)
FullArgSpec(args=['bar', 'baz', 'spam'], varargs=None, varkw='kw', defaults=('eggs',), kwonlyargs=['monty'], kwonlydefaults={'monty': 'python'}, annotations={'baz': <class 'list'>, 'return': None, 'spam': <class 'str'>, 'monty': <class 'str'>, 'bar': <class 'str'>})

inspect.getargspec() should be considered deprecated in Python 3.

Python 3.4 adds the inspect.Signature() object:

>>> inspect.signature(foo)
<inspect.Signature object at 0x100bda588>
>>> str(inspect.signature(foo))
"(bar:str, baz:list, spam:str='eggs', *, monty:str='python', **kw) -> None"
>>> inspect.signature(foo).parameters
mappingproxy(OrderedDict([('bar', <Parameter at 0x100bd67c8 'bar'>), ('baz', <Parameter at 0x100bd6ea8 'baz'>), ('spam', <Parameter at 0x100bd69f8 'spam'>), ('monty', <Parameter at 0x100bd6c28 'monty'>), ('kw', <Parameter at 0x100bd6548 'kw'>)]))

and many more interesting options to play with signatures.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343