0

How do I use an inherited decorator in Python?

class Foo:
    @staticmethod
    def keyErrorOnRed(f, colour):
        if colour == "red":
            raise KeyError("Better dead than red")
        return lambda: f(*args, **kwargs)

class Bar(Foo):
    @keyErrorOnRed("red")
    def __init__(self, a, b):
        self.vars = a, b

if __name__ == '__main__':
    barObj = Bar('can', 'haz')
A T
  • 11,788
  • 17
  • 89
  • 150

2 Answers2

1
def keyErrorOnRed(colour):
    def decorate(f):
        def wrapped(*args, **kwargs):
            if colour == "red":
                raise KeyError("Better dead than red")
            return f(*args, **kwargs)
        return wrapped
    return decorate

class Bar(object):
    @keyErrorOnRed("black")  #keyErrorOnRed("black")(Bar.__init__)(self, a, b)
    def __init__(self, a, b):
        self.vars = a, b
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
0

The technically correct answer :

class Bar(Foo):
    @Foo.KeyErrorOnRed
    def __init__(self, a, b):
        self.vars = a, b

BUT what's the point of making it a staticmethod when a plain function would do ?

bruno desthuilliers
  • 72,252
  • 6
  • 79
  • 103
  • For convenient namespacing. Also have some member variables in the parent class. Wait, so no `@` is needed? - Edit: this isn't working - http://ideone.com/gYStaM – A T Sep 19 '13 at 11:36
  • Yes the '@' is required, my mistake. wrt/ namespacing, modules are namespaces too. I sometimes use staticmethods instead of functions so I can rely on class-based dispatch, but that's not the case here since you do have to hardcode the parent's class name anyway. – bruno desthuilliers Sep 23 '13 at 07:16