Skip
Skip

Reputation: 6521

How to exit when assertion fails in python?

I would like to use assertions, so that my script exists, when assertions fail.

For that I wrote an own function, which stops the script

def assertExit(mlambda, errorMessage):
    res = mlambda()
    if res != True:
        sys.exit(errorMessage)

assertExit((lambda: False), "Should fail")

Is there a way to do that with pythons native assertions?

assert False # should exit the script

Upvotes: 5

Views: 8181

Answers (1)

deepbrook
deepbrook

Reputation: 2656

As has been pointed out, an unhandled AssertionError, as thrown by assert, should already stop your script.

assert always fails if the condition being tested doesn't evaluate to True. That is as long as you do not run python with optimizations enabled (-O flag), in which case it will not throw an AssertionError (as assert statements are skipped in optimized mode).

So

def assert_exit(condition, err_message):
    try:
        assert condition
    except AssertionError:
        sys.exit(err_message)

Should be what you want, if you absolutely want to call sys.exit() and use assert; However this

assert condition

will stop your script just as fine and provide a stacktrace, which saves you the trouble of entering a custom error message each time you call assert_exit, and points you directly to the offending party.

Upvotes: 5

Related Questions