Python warnings.warn
Capture a warning about an estimated delivery time so the program can report it and continue.
A simple example
warnings.warn
- Start with A calculation emits a RuntimeWarning
- Do this Run with the default warning action
- Result Warning, then execution continues
Syntax
warnings.warn(message, RuntimeWarning)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyContinue an estimate after reporting a warning
An estimate can still be useful when an input triggers a warning. Report the questionable condition to the caller while allowing the rest of the calculation to complete under the stated assumptions.
import warnings
with warnings.catch_warnings(record=True) as log:
warnings.simplefilter("always")
warnings.warn("Delivery time estimated", RuntimeWarning)
print(log[0].category.__name__)
print("Estimate ready")
RuntimeWarning Estimate ready
The warning is recorded and the following statement still runs. Python warning filters control what happens to the warning.
Flag an estimated wait
A queue display uses an estimate because the last reading is old. The record is still usable. Capture the warning while continuing the job and read the message shown to the operator.
Flag a missing optional room
A roster can still print while a room is being assigned. The record is still usable. Capture the warning while continuing the job and read the message shown to the operator.
What to watch for
Other languages use different severity categories. A warning should give the caller enough context to decide whether to continue.