serhii.net

In the middle of the desert you can say anything you want

14 Feb 2022

python asserts

After writing if x not in y: raise ValueError()... for the Nth time, thought of using an assert, and you can happily do something similar:

assert x in y, f"{x} should be inside {y}"

black formats that into

assert (
	x in y
), f"{x} should be inside {y}"

which looks nice too. That’s much faster to write than my usual ValueError pattern.

UsingAssertionsEffectively - Python Wiki touches on that, quoting from it directly below without changes.

Places to consider putting assertions:

  • checking parameter types, classes, or values
  • checking data structure invariants
  • checking “can’t happen” situations (duplicates in a list, contradictory state variables.)
  • after calling a function, to make sure that its return is reasonable
  • The overall point is that if something does go wrong, we want to make it completely obvious as soon as possible.

[…]

Assertions should not be used to test for failure cases that can occur because of bad user input or operating system/environment failures, such as a file not being found. Instead, you should raise an exception, or print an error message, or whatever is appropriate. One important reason why assertions should only be used for self-tests of the program is that assertions can be disabled at compile time.

Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus