Functools.update_wrapper () function does not work properly

I use Functools.update_wrapper() in my decorator, but it seems that update_wrapper only overwrites function attributes (such as __doc__ , __name__ ), but does not affect the help() function.

I know these answers , but they do not work with the decorator class.

Here is my function.

 import functools class memoized(object): def __init__(self, func): self.func = func functools.update_wrapper(self, func) def __call__(self, *args): self.func(*args) @memoized def printer(arg): "This is my function" print arg 

Here is the conclusion

 >>> printer.__doc__ This is my function >>> help(printer) Help on memoized in module __main__ object: printer = class memoized(__builtin__.object) | Methods defined here: | | __call__(self, *args) | | __init__(self, func) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) 

Sounds like a mistake, but how can I fix it?

+3
python decorator python-decorators functools
Sep 22 '14 at 11:47
source share
1 answer

functools.update_wrapper() sets the attribute on the instance, but help() looks at the type information.

So printer.__doc__ gives you an instance attribute, help() prints information about type(printer) , for example. a memoized class that does not have the __doc__ attribute.

This is not a mistake; it is all by design; help() will always look at the class when passing the instance . Do not use the class as a decorator if you want help() work for a decorated function.

+7
Sep 22 '14 at 11:50
source share



All Articles