How to get method parameter names?

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

    In python 3, below is to make *args and **kwargs into a dict (use OrderedDict for python < 3.6 to maintain dict orders):

    from functools import wraps
    
    def display_param(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
    
            param = inspect.signature(func).parameters
            all_param = {
                k: args[n] if n < len(args) else v.default
                for n, (k, v) in enumerate(param.items()) if k != 'kwargs'
            }
            all_param .update(kwargs)
            print(all_param)
    
            return func(**all_param)
        return wrapper
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:59

    What about dir() and vars() now?

    Seems doing exactly what is being asked super simply…

    Must be called from within the function scope.

    But be wary that it will return all local variables so be sure to do it at the very beginning of the function if needed.

    Also note that, as pointed out in the comments, this doesn't allow it to be done from outside the scope. So not exactly OP's scenario but still matches the question title. Hence my answer.

    0 讨论(0)
提交回复
热议问题