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
  • 13,008
  • 21
  • 97
  • 158

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
  • 244,495
  • 58
  • 464
  • 504
  • What's the most concise way of doing this with `keyErrorOnRed` being `@staticmethod` of parent class? – A T Sep 19 '13 at 11:39
  • @AT Just put this function in that class(`Foo`), and use `@Foo.keyErrorOnRed("black")` as the decorator in `Bar` class. – Ashwini Chaudhary Sep 19 '13 at 11:43
  • Great, thanks. ([black [not failing]](http://ideone.com/JmONvR), [red [failing]](http://ideone.com/A9L2xM)). Perfect! – A T Sep 19 '13 at 12:28
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
  • 75,974
  • 6
  • 88
  • 118
  • 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