Question

I often want have my Python code die if some condition isn't satisfied. I usually just use assert whatever(). However, I sometimes run with __debug__ equal to False. In these cases, there are still some assert-like conditions that I want to check for. I believe the "right" way to handle these cases is just a regular if: if not whatever(): raise Exception('Error message!'). In other words, I believe it's only correct to use assert for checks that you'd be happy to do without, presumably those that are time-consuming or that will be run many times. Is there a terser way to accomplish the same thing as the full conditional?

In Perl I would just use whatever() or die. Of course, given the philosophical differences between the languages it's hardly a surprise to see Perl require fewer characters.

Was it helpful?

Solution

One thing you could do is to create your own version of assert:

def confirm(expression):
    if not expression:
        raise AssertionError

Then, instead of using assert whatever(), you could instead do confirm(whatever()).

Alternatively, if you want to emulate perl, you could do the following:

def die():
    raise Exception()

whatever() or die()

If whatever() returns True, die() will never execute (due to boolean short-circuiting), and the program will merrily chug away. If whatever() returns False, then the program will terminate.

Technically, this is two more characters then perl, but you could rename die to d, and end up writing the same amount of characters.

I'm pretty sure that this isn't a Pythonic way of doing things, but the option is available, if you prefer it that way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top