The last time I wrote a bunch of decorators, I was writing python bindings to a set of C++ classes that each had an internal error state that had to be checked after each time a method was called to see if the method failed. If the error state was set, then subsequent method calls for the same object would fail silently, so it was crucial that the error state be checked. There were dozens of methods per class.
I ended up writing a class decorator that would decorate each method with the appropriate method decorator. The method decorator would call the GetErrorCode method, check if nonzero, reset the error state of the object, and then raise an appropriate python exception if necessary.
Major surgery to change the error handling in the called C++ code was not an option.
Can you suggest a better approach?
def doStuff():
# do stuff
return checkError(value)
@checkError
def doStuff():
# do stuff
return value
EDIT: In fact, I think the above succinctly hits on lotsoflumens' point. The latter clearly obfuscates the fact that an error check is performed behind the decorator. The former makes it very clear that something is happening to the return value before it leaves.Just because you can introspect a thing does not mean you must introspect that thing.