manipulating class attributes from a decorator while the class is being defined
Gerard Flanagan
grflanagan at gmail.com
Mon Apr 21 08:23:40 EDT 2008
On Apr 19, 11:19 pm, Wilbert Berendsen <wbs... 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?
>
> Thanks for any help,
> Wilbert Berendsen
>
> --http://www.wilbertberendsen.nl/
> "You must be the change you wish to see in the world."
> -- Mahatma Gandhi
---------------------------------------------------
def reg(regexp):
def deco(func):
def inner(self, *args, **kw):
if not hasattr(self, 'regexps'):
self.regexps = []
self.regexps.append((regexp, func))
return func(self, *args, **kw)
return inner
return deco
class Parser(object):
regexps = []
@reg(r'".*"')
def quoted_string(self):
print 'hi'
p = Parser()
p.quoted_string()
print p.regexps
---------------------------------------------------
More information about the Python-list
mailing list