Python cProfile - 装饰函数遮蔽了配置文件可视化 [英] Python cProfile - decorated functions obscuring profile visualization

查看:67
本文介绍了Python cProfile - 装饰函数遮蔽了配置文件可视化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a base class with a @classmethod which acts as a decorator for a large number of methods in many descendant classes.

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 的数千次调用.

When I profile this code and look at it through a tree view, I see thousands of calls to some_decorator from hundreds of different places.

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

And then I see some_decorator call back out to hundreds of the places it just came from.

这很烦人,我还没有找到解决方法,既不是通过更改代码也不是通过不同的方式进行分析.(使用 gprof2dot atm:如何获取调用树使用 python 分析器?)

It's quite annoying and I have yet to figure out a way around it, neither through changing the code nor profiling a different way. (Using gprof2dot atm: How can you get the call tree with python profilers?)

想法?

推荐答案

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

There are ways to build decorators to preserve docs/signatures. The wrapt library provides a lot of functionality to that end.

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)

这篇关于Python cProfile - 装饰函数遮蔽了配置文件可视化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆