I have some code like
class EventHandler:
def handle(self, event):
pass
def wrap_handler(handler):
def log_event(proc, e):
print e
proc(e)
handler.handle = lambda e: log_event(handler.handle, e)
handler = EventHandler()
wrap_handler(handler)
handler.handle('event')
that will end up with infinite recursion. While changing wrap_handler to
def wrap_handler(handler):
def log_event(proc, e):
print e
proc(e)
# handler.handle = lambda e: log_event(handler.handle, e)
handle_func = handler.handle
handler.handle = lambda e: log_event(handle_func, e)
the program will become OK. Why is that? And could anyone tell me more common ways to wrap functions?
It ends in an infinite recursion as when
lambda e: log_event(handler.handle, e)is called,handler.handleis already the lambda expression.log_eventwould call the lambda and the lambda would calllog_event, etc..To fix this, just save the current method in the local-scope, this also does not need the additional lambda-expression.
You could also use a decorator.