"or die()" in Python

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]?


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.


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.


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.


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.