【问题标题】:Dynamically Defining a Dummy Decorator动态定义一个虚拟装饰器
【发布时间】:2020-03-31 18:25:40
【问题描述】:

我正在使用一个名为https://github.com/rkern/line_profiler的好工具

要使用它,您需要在脚本中的多个位置放置一个装饰器@profile,以指示应该分析哪些函数。然后你通过执行脚本 kernprof -l script_to_profile.py

显然,当通过python script_to_profile.py 自行运行脚本时,没有定义装饰器,因此脚本会崩溃。

我知道如何定义一个标识装饰器,我可以从命令行传递一个标志,并根据标志的设置方式在主脚本中定义它。但是,我不知道如何将装饰器定义(或标志)传递给我加载的模块,以便它们在加载时不会崩溃。有什么想法吗?

def profile(func):
        return func

【问题讨论】:

  • 似乎您可以编写代码来检查是否定义了一个名为 profile 的函数,如果没有,请将其定义为身份装饰器。
  • 是的,我认为这会很好地工作!有没有指针可以查询是否定义了装饰器?

标签: python decorator python-decorators


【解决方案1】:

一个非常简单的方法是检查名为profile 的东西是否存在,如果不存在,则将其定义为您的身份装饰器。像这样。

try:
    profile
except NameError:
    def profile(func):
        return func

你可以更进一步,确保它是可调用的——可能没有必要:

import typing

try:
    profile
except NameError:
    profile = None

if not isinstance(profile, typing.Callable):
    def profile(func):
        return func

【讨论】:

  • 我用 line profiler 测试了它,它可以工作!谢谢!
猜你喜欢
  • 2010-10-14
  • 2020-01-06
  • 2011-09-03
  • 2021-12-17
  • 2013-02-06
  • 2017-06-19
  • 1970-01-01
  • 2017-08-11
  • 2017-10-12
相关资源
最近更新 更多