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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With