How to get method parameter names?

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

    In a decorator method, you can list arguments of the original method in this way:

    import inspect, itertools 
    
    def my_decorator():
    
            def decorator(f):
    
                def wrapper(*args, **kwargs):
    
                    # if you want arguments names as a list:
                    args_name = inspect.getargspec(f)[0]
                    print(args_name)
    
                    # if you want names and values as a dictionary:
                    args_dict = dict(itertools.izip(args_name, args))
                    print(args_dict)
    
                    # if you want values as a list:
                    args_values = args_dict.values()
                    print(args_values)
    

    If the **kwargs are important for you, then it will be a bit complicated:

            def wrapper(*args, **kwargs):
    
                args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))
                args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))
                args_values = args_dict.values()
    

    Example:

    @my_decorator()
    def my_function(x, y, z=3):
        pass
    
    
    my_function(1, y=2, z=3, w=0)
    # prints:
    # ['x', 'y', 'z', 'w']
    # {'y': 2, 'x': 1, 'z': 3, 'w': 0}
    # [1, 2, 3, 0]
    

提交回复
热议问题