Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

assert

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?

like image 648
Gattster Avatar asked Jan 26 '10 19:01

Gattster


People also ask

What is the use of assert statement in Python?

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.

What does Python say the assert statement best used for and what is it not recommended for and why )?

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.

When should assert be used?

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.

Why do we use assert statements in code?

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.


2 Answers

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.

like image 174
rob Avatar answered Sep 21 '22 15:09

rob


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:

  1. The error is totally, 100% fatal, and dealing with it would be too grim to comprehend
  2. The assert should only fail if something causes the laws of logic to change

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!

like image 29
Aiden Bell Avatar answered Sep 22 '22 15:09

Aiden Bell