Class decorator with argument

Terry Reedy tjreedy at udel.edu
Fri Jan 16 20:11:44 EST 2009


mk wrote:
> Hello,
> 
> I wrote this class decorator with argument:

The following is a *function* decorator, with the twist of being an 
instance of a user class rather than of the built-in function class (one 
I had not thought of).

A class decorator would be a callable the modifies or wraps a *class*.

>  >>> class ChangeDoc(object):
>     def __init__(self, docstring):
>         self.docstring = docstring
>     def __call__(self, func):
>         func.__doc__ = self.docstring
>         return func
> 
> It seems to work:
> 
>  >>> @ChangeDoc("bulba")
> def f():
>     pass
> 
>  >>> f.__doc__
> 'bulba'
> 
> Can someone please debug my reasoning if it's incorrect?
> 
> 1. First, the decorator @ChangeDoc('bulba') instantiates with 
> __init__(self, 'bulba'), to some class instance, let's call it _decor.
> 
> 2. Then _decor's __call__ method is called with function f as argument, 
> changing the docstring and returning the changed f object, like f = 
> _decor(f) .
> 
> Am I missing smth important / potentially useful in typical real-world 
> applications in that picture?




More information about the Python-list mailing list