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 -- http://mail.python.org/mailman/listinfo/python-list