将默认参数传递给 python 中的装饰器 [英] Passing default arguments to a decorator in python

查看:28
本文介绍了将默认参数传递给 python 中的装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法将我的函数的默认参数传递给装饰器.我不得不说我对装饰行业还很陌生,所以也许我只是没有正确理解它,但我还没有找到任何答案.

I am trying to find a way to pass my function's default arguments to the decorator. I have to say I am fairly new to the decorator business, so maybe I just don't understand it properly, but I have not found any answers yet.

所以这是我从 Python functools 中修改的示例.包装手册页.

So here's my modified example from the Python functools.wraps manual page.

from functools import wraps
def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
            print('Calling decorated function')
            print('args:', args)
            print('kwargs:', kwds)
            return f(*args, **kwds)
    return wrapper

@my_decorator
def example(i, j=0):
    """Docstring"""
    print('Called example function')

example(i=1)

我也希望 j=0 被传递.所以输出应该是:

I want the j=0 to be passed, too. So the output should be:

Calling decorated function
args: ()
kwargs: {'i': 1, 'j': 0}
Called example function

但我得到了

Calling decorated function
args: ()
kwargs: {'i': 1}
Called example function

推荐答案

默认参数是函数签名的一部分.它们不存在于装饰器调用中.

Default arguments are part of the function's signature. They do not exist in the decorator call.

要在包装器中访问它们,您需要将它们从函数中取出,如 这个问题.

To access them in the wrapper you need to get them out of the function, as shown in this question.

import inspect
from functools import wraps

def get_default_args(func):
    signature = inspect.signature(func)
    return {
        k: v.default
        for k, v in signature.parameters.items()
        if v.default is not inspect.Parameter.empty
    }

def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
            print('Calling decorated function')
            print('args:', args)
            kwargs = get_default_args(f)
            kwargs.update(kwds)
            print('kwargs:', kwargs)
            return f(*args, **kwds)
    return wrapper

@my_decorator
def example(i, j=0):
    """Docstring"""
    print('Called example function')

example(i=1)

输出:

Calling decorated function
args: ()
kwargs: {'i': 1, 'j': 0}
Called example function

这篇关于将默认参数传递给 python 中的装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆