[Tutor] Decorators, I am confused.

Kent Johnson kent37 at tds.net
Fri Jul 15 05:17:39 CEST 2005


David Driver wrote:
> What I would like to do is something like this:
> 
> class testObj(object):
>     _rules = list()
>     def evalRules(self):
>         for r in _rules:
>             r()
>     def rule(func):
>         if not func in func.__class__._rules:
>             func.__class__._rules.append(func)
>             print testis._rules
>         return func
>     @rule
>     def arule(self):
>         print a
> 
> Of course it doesn't work. Is there a way to make it work? What I am
> trying to do is make a collection of validation rules that can be
> iterated and capture raised exceptions to be returned at the end of
> eval rules.

Here is one way to do it. The rule() decorator just adds an attribute to the function that marks it as a rule. You could also use a naming convention to mark rules. The __init__ method uses inspection of dir(self) to find the rules. Because dir() includes base class attributes it works with inherited rule classes which IIRC was something you wanted.

def rule(func):
    func.isRule = True
    return func

class testObj(object):
    def __init__(self):
        self._rules = []
        for name in dir(self):
            item = getattr(self, name)
            if getattr(item, 'isRule', False):
                self._rules.append(item)
        
    def evalRules(self):
        for r in self._rules:
            r()

    @rule
    def arule(self):
        print 'This is a rule'
    
    @rule
    def brule(self):
        print 'This is another rule'

t = testObj()
t.evalRules()


class testObj2(testObj):
    @rule
    def arule(self):
        print 'This is a new version of arule'

t = testObj2()
t.evalRules()



More information about the Tutor mailing list