用另一个装饰器包裹python装饰器

发布于 2025-02-06 14:18:01 字数 534 浏览 1 评论 0原文

在我的Django代码库中,我都有一个通用的装饰器呼叫:

@override_settings(
    CACHES={
        **settings.CACHES,
        "default": generate_cache("default", dummy=False),
        "throttling": generate_cache("throttling", dummy=False),
    }
)
def test_something():
    ...

装饰器代码太冗长了。我想将此代码包装到一个名为@use_real_cache的新装饰器中,因此测试功能看起来更干净:

@use_real_cache
def test_something():
    ...

如何用另一个装饰器将装饰器包裹起来?

I have a common decorator call throughout my Django codebase:

@override_settings(
    CACHES={
        **settings.CACHES,
        "default": generate_cache("default", dummy=False),
        "throttling": generate_cache("throttling", dummy=False),
    }
)
def test_something():
    ...

The decorator code is too verbose. I'd love to wrap this code into a new decorator called @use_real_cache so the test function looks much cleaner:

@use_real_cache
def test_something():
    ...

How can I wrap a decorator with another decorator?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

懒的傷心 2025-02-13 14:18:01

只需将其分配给一个值:

use_real_cache = override_settings(
    CACHES={
        **settings.CACHES,
        'default': generate_cache('default', dummy=False),
        'throttling': generate_cache('throttling', dummy=False),
    }
)

# …

@use_real_cache
def test_something():
    # …
    pass

这本质上是问题的第一个代码示例中发生的情况,只是您没有将其分配给(显式)变量。

Just assign it to a value:

use_real_cache = override_settings(
    CACHES={
        **settings.CACHES,
        'default': generate_cache('default', dummy=False),
        'throttling': generate_cache('throttling', dummy=False),
    }
)

# …

@use_real_cache
def test_something():
    # …
    pass

This is essentially what happens in the first code sample of the question, except that you do not assign it to an (explicit) variable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文