提供您自己的传递无操作版本,而不是删除装饰器行。@profile
您可以在某处将以下代码添加到您的项目中:
try:
# Python 2
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
try:
builtins.profile
except AttributeError:
# No line profiler, provide a pass-through version
def profile(func): return func
builtins.profile = profile
在使用装饰器的任何代码之前导入此代码@profile
,您可以在有或没有激活线分析器的情况下使用代码。
因为虚拟装饰器是一个传递函数,执行性能不受影响(只有导入性能受到轻微影响)。
如果你不喜欢弄乱内置插件,你可以把它做成一个单独的模块;说profile_support.py
:
try:
# Python 2
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
try:
profile = builtins.profile
except AttributeError:
# No line profiler, provide a pass-through version
def profile(func): return func
(没有分配给builtins.profile
)并在使用装饰器from profile_support import profile
的任何模块中使用。@profile