Python convert args to kwargs

前端 未结 6 1040
南方客
南方客 2021-02-05 07:57

I am writing a decorator that needs to call other functions prior to call of the function that it is decorating. The decorated function may have positional arguments, but the f

6条回答
  •  后悔当初
    2021-02-05 08:09

    Nadia's answer is correct, but I feel like a working demo of that answer is useful.

    def decorator(func):
        def wrapped_func(*args, **kwargs):
            kwargs.update(zip(func.__code__.co_varnames, args))
            print(kwargs)
            return func(**kwargs)
        return wrapped_func
    
    @decorator
    def thing(a,b):
        return a+b
    

    Given this decorated function, the following calls return the appropriate answer:

    thing(1, 2)  # prints {'a': 1, 'b': 2}  returns 3
    thing(1, b=2)  # prints {'b': 2, 'a': 1}  returns 3
    thing(a=1, b=2)  # prints {'a': 1, 'b': 2}  returns 3
    

    Note however that things start getting weird if you start nesting decorators because the decorated function now no longer takes a and b, it takes args and kwargs:

    @decorator
    @decorator
    def thing(a,b):
        return a+b
    

    Here thing(1,2) will print {'args': 1, 'kwargs': 2} and error with TypeError: thing() got an unexpected keyword argument 'args'

提交回复
热议问题