문제

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?

도움이 되었습니까?

해결책 2

You want inspect.getargspec:

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

다른 팁

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')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top