"or die()" in Python

Question:

Is anyone using anything like this in Python:

def die(error_message):
    raise Exception(error_message)

...

check_something() or die('Incorrect data')

I think this kind of style is used in PHP and Perl.

Do you find any (dis)advantages in this [style]?

Asked By: warvariuc

||

Answers:

It seems like you are just wrapping php lingo in python with a one line function. I would advise against it as you might confuse your audience. Exceptions are also a completely different beast than die in PHP.

Answered By: user847229

The biggest disadvantage is that all dying is now the same. Better to have check_something() raise a more accurate exception and then catch that up above if appropriate.

While that style is common in PHP and Perl, it’s very un-Pythonic and I’d encourage you not to write Python that way. You should follow the conventions in the language you’re using, and write something like this:

if not check_something():
    raise Exception('Incorrect data')

FWIW, doing the “or die(…)” way adds another level to your stack trace, which is another minor disadvantage.

Answered By: Keith Devens

Well, first, sys.exit([arg]) is more common, and if you really wanted something equivalent to die in PHP, you should use that, raise a SystemExit error, or call os._exit.

The major use of the die method in PHP is, “The script has reached some impasse cannot recover from it”. It is rarely, if ever, used on production code. You are better off raising an exception in a called function, catching it in the parent, and finding a graceful exit point — that is the best way in both languages.

Answered By: cwallenpoole

If you are dealing with an API that you didn’t write that returns truthy values on success and falsy values on failure, that seems like a reasonably readable and compact way to do it. If you have control over the API, I’d encourage you to use exceptions instead of return values to indicate errors.

If you use the function, it probably should not be called die() unless it actually exits the program, however. If it merely raises an exception, there’s no guarantee that the program will actually die. Ideally you could name it raise() as a functional version of the raise statement, but of course you can’t because raise is a reserved word. Perhaps throw().

It would also be a good idea to require the caller to pass in an exception type, since Exception is rather generic and vague.

It occurs to me that this function would be unnecessary if only Python exceptions were capable of raising themselves, i.e., they had a method for it, like so:

class BaseException(object):
     def throw(self):
         raise self

Then you could just do:

check_something() or Exception("check failed").throw()

Sadly, Python exceptions can’t raise themselves. 🙂

Answered By: kindall

Lot’s of good answers, but no-one has yet suggested the obvious way to write this in Python:

assert check_something(), "Incorrect data"

Just be aware that it won’t do the check if you turn on optimisation, not that anyone ever does.

Answered By: Duncan

Ideally, you would want to die/panic with a helpful stack-trace so that you can easily locate the issue.
Hence, unlike the most popular answer, you should AVOID sys.exit() or raise a SystemExit because they will cause your program to die silently(without a helpful trace).

You should use a general exception like RuntimeError that is most likely not going to be handled/caught later, and it will create a beautiful stack-trace:

def die(message):
    raise RuntimeError(message)


print("hello world")
die('A helpful message')
print("hello world again")

We get the following helpful stack trace:

hello world
Traceback (most recent call last):
  File "/test.py", line 9, in <module>
    die("A helpful message")
  File "/test.py", line 5, in die
    raise RuntimeError(message)
RuntimeError: A helpful message

If I had used sys.exit instead, I would have gotten the following poor output:

import sys

def die(message):
    sys.exit(message) # internally raises SystemExit

print("hello world")
die("A helpful message")
print("hello world again")
hello world
A helpful message
Answered By: Harsh Verma
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.