繁体   English   中英

动态定义一个虚拟装饰器

[英]Dynamically Defining a Dummy Decorator

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

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

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

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

def profile(func):
        return func

一个非常简单的方法是检查命名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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM