manipulating class attributes from a decorator while the class is being defined
Duncan Booth
duncan.booth at invalid.invalid
Mon Apr 21 05:44:43 EDT 2008
Wilbert Berendsen <wbsoft at xs4all.nl> wrote:
> 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?
>
Have you tried passing regexps into the decorator as a default argument?
def reg(regexp, regexps=regexps):
def deco(func):
regexps.append((regexp, func))
return func
return deco
More information about the Python-list
mailing list