functools.wraps equivalent for class decorator

后端 未结 2 1002
[愿得一人]
[愿得一人] 2021-02-14 07:16

When we decorate function, we use functools.wraps to make decorated function look like original.

Is there any wat to do same, when we want to decorate class?

<         


        
2条回答
  •  醉话见心
    2021-02-14 08:09

    No, there isn't, assuming your decorator really subclasses the wrapped class like some_class_decorator does. The output of help is defined by the pydoc.Helper class, which for classes ultimately calls pydoc.text.docclass, which contains this code:

    # List the mro, if non-trivial.
    mro = deque(inspect.getmro(object))
    if len(mro) > 2:
        push("Method resolution order:")
        for base in mro:
            push('    ' + makename(base))
        push('')
    

    You can see that it is hard-coded to display the class's real MRO. This is as it should be. The MRO displayed in your last example is not "broken", it is correct. By making your wrapper class inherit from the wrapped class, you added an additional class to the inheritance hierarchy. It would be misleading to show an MRO that left that out, because there really is a class there. In your example, this wrapper class doesn't provide any behavior of its own, but a realistic wrapper class would (or else why would you be doing the wrapping at all?), and you would want to know which behavior came from the wrapper class and which from the wrapped class.

    If you wanted, you could make a decorator that dynamically renamed the wrapper class with some name derived from the original, so the MRO would show something like DecoratorWrapper_of_MainClass in the appropriate position. Whether this would be more readable than just having Wrapper there is debatable.

提交回复
热议问题