How to get method parameter names?

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

    In CPython, the number of arguments is

    a_method.func_code.co_argcount
    

    and their names are in the beginning of

    a_method.func_code.co_varnames
    

    These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.

    One portable way to admit "pass-through" arguments is to define your function with the signature func(*args, **kwargs). This is used a lot in e.g. matplotlib, where the outer API layer passes lots of keyword arguments to the lower-level API.

提交回复
热议问题