python - Register unique callbacks per instance using classmethod -
i wanted make easier register callbacks using decorators when designing library, problem both use same instance of consumer.
i trying allow both these examples co-exist in same project.
class simpleconsumer(consumer): @consumer.register_callback def callback(self, body) print body class advancedconsumer(consumer): @consumer.register_callback def callback(self, body) print body = advancedconsumer() s = simpleconsumer()
what happens here callback implementation of advancedconsumer override 1 of simpleconsumer, defined last.
the implementation of decorator class pretty simple.
class consumer(object): def start_consumer(self): self.consuming_messages(callback=self._callback) @classmethod def register_callback(cls, function): def callback_function(cls, body): function(cls, body) cls._callback = callback_function return callback_function
i happy implementation, there possibility register second callback ensure won't problem in future. so, have suggestion on how implement in way not static?
the implementation shown here simplified, , precaution have in code.
if cls._callback: raise runtimeerror('_callback method defined')
you can class decorator:
def register_callback(name): def decorator(cls): cls._callback = getattr(cls, name) return cls return decorator @register_callback('my_func') class simpleconsumer(consumer): def my_func(self, body): print body
if want decorate method, function in cannot access information class method contained in.
but if 1 callback should available per class why not call _callback
?
class simpleconsumer(consumer): def _callback(self, body): print body
or like:
class simpleconsumer(consumer): def my_func(self, body): print body _callback = my_func
?
Comments
Post a Comment