Gattster Gattster - 1 year ago 74
Python Question

What are acceptable use-cases for python's `assert` statement?

I often use python's assert statement to check user input and fail-fast if we're in a corrupt state. I'm aware that assert gets removed when python with the

(optimized) flag. I personally don't run any of my apps in optimized mode, but it feels like I should stay away from assert just in-case.

It feels much cleaner to write

assert filename.endswith('.jpg')


if not filename.endswith('.jpg'):
raise RuntimeError

Is this a valid use case for assert? If not, what would a valid use-case for python's
statement be?

Answer Source

Assertions should be used for expressing invariants, or preconditions.
In your example, you are using them for checking unexpected input - and that's a completely different class of exceptions.

Depending on the requirements, it may be perfectly OK to raise an exception on wrong input, and stop the application; however the code should always be tailored for expressiveness, and raising an AssertionError is not that explicit.
Much better would be to raise your own exception, or a ValueError.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download