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 -o
(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')
than
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 assert
statement be?
The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.
The Python assert keyword tests if a condition is true. If a condition is false, the program will stop with an optional message. Assert statements are used to debug code and handle errors. You should not use an assert statement in a production environment.
Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen. For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.
An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
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
.
If being graceful is impossible, be dramatic
Here is the correct version of your code:
if filename.endswith('.jpg'): # convert it to the PNG we want try: filename = convert_jpg_to_png_tmpfile(filename) except PNGCreateError: # Tell the user their jpg was crap print "Your jpg was crap!"
It is a valid case, IMHO when:
Otherwise, deal with the eventuality because you can see it coming.
ASSERT == "This should never occur in reality, and if it does, we give up"
Of course, this isn't the same as
#control should never get here
But I always do
#control should never get here #but i'm not 100% putting my money where my mouth #is assert(False)
That way I get a nice error. In your example, I would use the if
version and convert the file to jpg!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With