How to get method parameter names?

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

提交回复
热议问题