I have a simple exception-logging decorator, which is handy for sending myself emails when my scripts throw exceptions.
def logExceptions(func):
def wrapper():
try:
func()
except Exception, e:
logger.exception(e)
return wrapper
However, if I want to decorate a class method, I have to modify wrapper() to take a ‘self’, otherwise I get the following error:
TypeError: wrapper() takes no arguments (1 given)
Of course, at that point I can’t use it to decorate any non-class methods, because then this error occurs:
TypeError: wrapper() takes exactly 1 argument (0 given)
Is there a clean way to tackle this problem? Thank you =)
The usual thing is to define your wrapper so it accepts
*argsand**kwargsand passes them on to the function it wraps. This way it can wrap any function.Also, I get the impression that what you are calling a “class method” is what Python calls an “instance method”, and what you call “non-class method” is what Python calls a “function”. A “non-class method” (e.g., instance method) in Python takes a
selfargument.