How to get method parameter names?

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

    To update a little bit Brian's answer, there is now a nice backport of inspect.signature that you can use in older python versions: funcsigs. So my personal preference would go for

    try:  # python 3.3+
        from inspect import signature
    except ImportError:
        from funcsigs import signature
    
    def aMethod(arg1, arg2):
        pass
    
    sig = signature(aMethod)
    print(sig)
    

    For fun, if you're interested in playing with Signature objects and even creating functions with random signatures dynamically you can have a look at my makefun project.

提交回复
热议问题