Python2.x元类生成的包装器break insp

2024-10-02 00:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题,我使用元类包装了一些类方法,但是现在如果我使用help()内置方法,这些方法将显示为包装器而不是原始方法。你知道吗

# Example:

class MetaBuilderModule(type):

    @staticmethod
    def time_method(method):
        @functools.wraps(method)
        def __wrapper(self, *args, **kwargs):
            if self.__timingstatus__[method.__name__]:
                return method(self, *args, **kwargs)

            else:
                # Set the timing status of the method to True so that we don't
                # time any inherited methods.
                self.__timingstatus__[method.__name__] = True

                start = time.time()
                finish = None
                result = None

                # Put the result behind a try / except so that if we get an error
                # within the method we can still reset the timing status.
                try:
                    result = method(self, *args, **kwargs)
                except Exception:
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    traceback.print_exception(exc_type, exc_value, exc_traceback)
                    self.__timingstatus__[method.__name__] = False
                    return False

                finish = time.time()

                sys.stdout.write('Instance method \'%s\' of BuilderModule class'
                    ' took %0.3fs to execute.\n' %(method.__name__, (finish - start)))

                # Reset the timing status.
                self.__timingstatus__[method.__name__] = False
                return result

        return __wrapper


    def __new__(cls, name, bases, attrs):
        # Create the __timingstatus__ dictionary that helps stop timers being
        # triggered by inherited methods.
        attrs['__timingstatus__'] = dict()

        for attr in ['__init__', 'run']:
            attrs['__timingstatus__'][attr] = False

            if not attr in attrs:
                continue

            attrs[attr] = cls.time_method(attrs[attr])

        return super(MetaBuilderModule, cls).__new__(cls, name, bases, attrs)

如你所见,我添加了@函数工具.wrapps对包装器方法进行修饰,这样至少我得到了正确的方法名,但仍然没有得到正确的参数。你知道吗

Example:

 |  Methods defined here:
 |  
 |    __init__(self, *args, **kwargs)

我看到一些文章建议猴子修补检查.getargspec但我认为这不是一个实际的解决方案。你知道吗

有人有什么其他的黑魔法吗?你知道吗

干杯

断路器


Tags: the方法nameselffalsereturntimeargs

热门问题