【问题标题】:Python cProfile - decorated functions obscuring profile visualizationPython cProfile - 修饰函数使配置文件可视化变得模糊
【发布时间】:2017-05-05 20:45:44
【问题描述】:

我有一个带有@classmethod 的基类,它充当许多后代类中大量方法的装饰器。

class BaseClass():
    @classmethod
    def some_decorator(cls, method):
        @wraps(method)
        def inner_method(self, *args, **kwargs):
            # do stuff
            return method(self, *args, **kwargs)
        return inner_method


class ChildClass(BaseClass):
    @BaseClass.some_decorator
    def some_child_method(self):
        # do other stuff
        return

当我分析这段代码并通过树形视图查看它时,我看到来自数百个不同地方的数千次对 some_decorator 的调用。

然后我看到some_decorator 回拨到它刚刚来自的数百个地方。

这很烦人,我还没有找到解决方法,既不是通过更改代码也不是通过其他方式分析。 (使用 gprof2dot 自动取款机:How can you get the call tree with python profilers?

想法?

【问题讨论】:

  • 由于装饰器通常为每个装饰函数创建一个闭包,你不能更新(或复制)代码对象并更改文件和行信息以引用装饰函数上方的行?

标签: python profiling cprofile pstats


【解决方案1】:

有一些方法可以构建装饰器来保存文档/签名。 wrapt 库为此提供了很多功能。

https://wrapt.readthedocs.io/en/latest/decorators.html#decorating-class-methods

它最终会看起来像这样:

class BaseClass():
    @wrapt.decorator
    @classmethod
    def some_decorator(cls, method, instance, *args, *kwargs):
        # do stuff
        return method(instance, *args, **kwargs)

【讨论】:

    猜你喜欢
    • 2014-10-27
    • 2021-01-05
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2014-03-07
    • 2012-12-06
    • 2011-04-03
    • 1970-01-01
    相关资源
    最近更新 更多