manipulating class attributes from a decorator while the class is being defined

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Apr 21 04:35:51 EDT 2008


Wilbert Berendsen a écrit :
> Hi, is it possible to manipulate class attributes from within a decorator 
> while the class is being defined?
> 
> I want to register methods with some additional values in a class attribute. 
> But I can't get a decorator to change a class attribute while the class is 
> still being defined. Something like:
> 
> class Parser(object):
>   
>   regexps = []
>   def reg(regexp):
>     def deco(func):
>       regexps.append((regexp, func))
>       return func
>     return deco
>   
>   @reg(r'".*"')
>   def quoted_string(self):
>     pass
> 
> How can I reach the class attribute `regexps' from within a decorator?

Simple answer : you can't. Because, as you noticed, the class object 
doesn't exist yet.

The canonical solutions are either to store regexps outside the class 
(ie: as a module level variable) - which can be problematic in some 
cases -, or to use a two-pass scheme using a decorator and a metaclass, 
where the decorator annotate the function with required informations for 
latter processing, and the metaclass do the effective processing.

There are of course other solutions, some of them possibly simpler. The 
'best' solution of course depends on intented use of your class...

HTH



More information about the Python-list mailing list