Reputation: 713
I am a relative beginner in Python and I am trying to use it to run some not-well-documented code. My question is, how can I get a list of possible arguments of a function or a class constructor using interactive shell, for example. Ideally, I would like to have something like dir(), but it should list not class members, but possible argument's names of a function.
If it is not possible, is there any other way to infer function arguments without looking inside the code?
Upvotes: 0
Views: 131
Reputation: 8205
You want inspect.getargspec
:
>>> import inspect
>>> def foo(bar, baz):
... pass
...
>>> inspect.getargspec(foo)
ArgSpec(args=['bar', 'baz'], varargs=None, keywords=None, defaults=None)
Upvotes: 1
Reputation: 1121524
Use help(function_object)
to have python format everything it knows about a given function for you.
You can also use the inspect.getargspec()
function to get a named tuple overview of the arguments accepted. You can pass the result of that function to inspect.formatargspec()
to format that as a python function as well:
>>> from inspect import getargspec, formatargspec
>>> def demo(foo, bar, eggs='ham'): pass
...
>>> getargspec(demo)
ArgSpec(args=['foo', 'bar', 'eggs'], varargs=None, keywords=None, defaults=('ham',))
>>> formatargspec(*getargspec(demo))
"(foo, bar, eggs='ham')"
For the above example function, help(demo)
prints:
Help on function demo in module __main__:
demo(foo, bar, eggs='ham')
Upvotes: 4