November 27th, 2014
In Technology
No Comments
If you enjoy this article, see the other most popular articles
If you enjoy this article, see the other most popular articles
If you enjoy this article, see the other most popular articles
Flask uses assertions
(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.
Assertions don’t seem to be used very often in Python, but they are used in Flask:
eugene-eeo started the conversation:
eugene-eeo commented 10 hours ago
I was browsing through the source and found it weird that asserts were used instead of normal exceptions.
untitaker replied:
Alright. Because Flask is using assert-statements exactly as usually recommended. The Python wiki explains the meaning of assertion errors:
Assertions are not a substitute for unit tests or system tests, but rather a complement. Because assertions are a clean way to examine the internal state of an object or function, they provide “for free” a clear-box assistance to a black-box test that examines the external behaviour.
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.
If this exception is raised, there is almost certainly a bug in Flask, and not the user’s code. I don’t have anything against providing a clearer error message, but raising AssertionError is completely fine in this situation.
DasIch added:
Definitely agree with @untitaker here. These asserts should never trigger and could in principle be removed. Their purpose is primarily documentation, in that they state clearly which pre-conditions or invariants should hold and secondarily ensure (particularly during testing and development) that a systematic failure that could violate the assumptions implied by the assert is caught early.
A RuntimeError on the other hand, may very well be raised if someone merely uses an API incorrectly.
Post external references
- 1
https://github.com/mitsuhiko/flask/pull/1258
February 8, 2022 9:33 am
From Michael S on How I recovered from Lyme Disease: I fasted for two weeks, no food, just water
"Did you have Bartonella, too? Seems it uses autogenesis..."