简体   繁体   English

动态定义一个虚拟装饰器

[英]Dynamically Defining a Dummy Decorator

I am using a nice tool called https://github.com/rkern/line_profiler我正在使用一个名为https://github.com/rkern/line_profiler的好工具

To use it, you need to put a decorator @profile at multiple places in the script to indicate which functions should be profiled.要使用它,您需要在脚本中的多个位置放置一个装饰器@profile以指示应分析哪些函数。 Then you execute the script via kernprof -l script_to_profile.py然后你通过kernprof -l script_to_profile.py执行脚本

Obviously, when running the script by itself via python script_to_profile.py , the decorator is not defined and hence the script crashes.显然,当通过python script_to_profile.py自行运行脚本时,装饰器未定义,因此脚本崩溃。

I know how to define an identity decorator and I can pass a flag from the command line and define it in the main script depending on how the flag is set.我知道如何定义标识装饰器,我可以从命令行传递一个标志,并根据标志的设置方式在主脚本中定义它。 However, I don't know how to pass the decorator definition (or the flag) to modules I load so they don't crash at the moment they are loaded.但是,我不知道如何将装饰器定义(或标志)传递给我加载的模块,以便它们在加载时不会崩溃。 Any ideas?有任何想法吗?

def profile(func):
        return func

A very simple way would be to check if something named profile exists, and if it doesn't, then define it to be your identity decorator.一个非常简单的方法是检查命名profile存在,如果不存在,则将其定义为您的身份装饰器。 Something like this.像这样的东西。

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

You could go a little further and make sure it's something callable — probably not necessary:你可以更进一步,确保它是可调用的——可能没有必要:

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