1

I have a method like so

def update_count(target, value, initiator):
  target.count = len(target.collection)

However, I have three decorator functions I wish to apply it to

@event.listens_for(MyClass.collection, 'append')
@event.listens_for(MyClass.collection, 'remove')
@event.listens_for(MyClass.collection, 'set')

Instead of copying the whole method below each decorator, what is a pythonic way to pass update_count to each of the event.listens_for decorator methods as a reference?

corvid
  • 10,733
  • 11
  • 61
  • 130

1 Answers1

1

Simplest:

@event.listens_for(MyClass.collection, 'append')
@event.listens_for(MyClass.collection, 'remove')
@event.listens_for(MyClass.collection, 'set')
def update_count(target, value, initiator):
    target.count = len(target.collection)

i.e, just put the decorators one after the other before def.

Of course, this may cause overhead, e.g if each decorator wraps the decorated function into another -- but if you can't fix the decorator, then you can't avoid that overhead. If you can change the decorator, then a listen_multi variant thereof, that takes all events being listened for in a single gulp, might no doubt offer much better performance.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395