5

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
3
  • 1
    Native assertions will raise an exception if they fail, which will terminate the application unless you catch it. Commented Aug 8, 2017 at 7:33
  • 1
    Simply not catching AssertionErrors should do the trick… why do you need an even more direct exit? Commented Aug 8, 2017 at 7:33
  • you are right, failed assertions do stop the script already. I was confused, because the logs order was wrong, and in the logs, after assertion exception, some output was logged Commented Aug 8, 2017 at 7:53

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.