How to get method parameter names?

前端 未结 15 2452
眼角桃花
眼角桃花 2020-11-22 09:14

Given the Python function:

def a_method(arg1, arg2):
    pass

How can I extract the number and names of the arguments. I.e., given that I h

15条回答
  •  爱一瞬间的悲伤
    2020-11-22 09:44

    Take a look at the inspect module - this will do the inspection of the various code object properties for you.

    >>> inspect.getfullargspec(a_method)
    (['arg1', 'arg2'], None, None, None)
    

    The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.

    >>> def foo(a, b, c=4, *arglist, **keywords): pass
    >>> inspect.getfullargspec(foo)
    (['a', 'b', 'c'], 'arglist', 'keywords', (4,))
    

    Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a ValueError if you use inspect.getfullargspec() on a built-in function.

    Since Python 3.3, you can use inspect.signature() to see the call signature of a callable object:

    >>> inspect.signature(foo)
    
    

提交回复
热议问题