So lately I've been asking a few questions about more professional and pythonic style in Python, and despite being given great answers to my questions, I feel like I need to ask a much broader question.
In general, when writing utility functions (for a library, etc.) that deal more with side effects (file writes, dictionary definitions, etc.) than return values, it's very useful to return a status code to tell the calling function that it passed or failed.
In Python, there seem to be three ways to flag this:
Using a return value of -1 or 0 (C like) and using statements such as
if my_function(args) < 0:
fail condition
pass condition
or using a return value of True/False
if not my_function(args):
fail condition
pass condition
or using a 'return or 'return None' using exceptions (exits on unknown error)
try:
my_function(args)
except ExpectedOrKnownExceptionOrError:
fail condition
pass condition
Which of these is best? Most correct? Preferred? I understand all work, and there isn't much technical advantage of one over the other (except perhaps the overhead of exception handling).
Don't return something to indicate an error. Throw an exception. Definitely don't catch an exception and turn it into a return code.
When an exception is raised and not caught, Python will exit with an error (non-zero) code for you. If you are defining your own exception types, you should override sys.excepthook() to provide you with the exit codes you desire, since they will by default use the exit code 1.
If you want to specify your exit code for some weird reason, use sys.exit() and the errno module to get the standard exit codes so that you will use the appropriate one. You can also use the traceback module to get the stack traceback (and it seems the correct error code as well, according to that answer). Personally, I don't prefer this approach either.
The approach I recommend is to not catch the exception; just let it happen. If your program can continue to operate after an exception occurs, you ought to catch it and handle it appropriately. However, if your program cannot continue, you should let the exception be. This is particularly useful for re-using your program in other Python modules, because you will be able to catch the exception if you so desire then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With