动态定义虚拟装饰器

我正在使用一种名为 https://github.com/rkern/line_profiler

要使用它,您需要在脚本中的多个位置放置一个装饰器,以指示应分析哪些功能。然后通过以下方式执行脚本@profilekernprof -l script_to_profile.py

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

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

def profile(func):
        return func


温温酱
浏览 112回答 1
1回答

沧海一幻觉

一种非常简单的方法是检查是否有名为名称的东西存在,如果不存在,则将其定义为您的身份装饰器。像这样的东西。profiletry:    profileexcept NameError:    def profile(func):        return func你可以走得更远一点,确保它是可调用的 —— 可能不是必需的:import typingtry:    profileexcept NameError:    profile = Noneif not isinstance(profile, typing.Callable):    def profile(func):        return func
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python