How to get method parameter names?

前端 未结 15 2131
眼角桃花
眼角桃花 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:53

    Python 3.5+:

    DeprecationWarning: inspect.getargspec() is deprecated, use inspect.signature() instead

    So previously:

    func_args = inspect.getargspec(function).args
    

    Now:

    func_args = list(inspect.signature(function).parameters.keys())
    

    To test:

    'arg' in list(inspect.signature(function).parameters.keys())
    

    Given that we have function 'function' which takes argument 'arg', this will evaluate as True, otherwise as False.

    Example from the Python console:

    Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
    >>> import inspect
    >>> 'iterable' in list(inspect.signature(sum).parameters.keys())
    True
    

提交回复
热议问题