Library contents

Python warnings.warn

Capture a warning about an estimated delivery time so the program can report it and continue.

A simple example

warnings.warn

  1. Start with A calculation emits a RuntimeWarning
  2. Do this Run with the default warning action
  3. Result Warning, then execution continues
The warning records a problem while still allowing a following statement to run.

Syntax

Python 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.py

Continue 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.

First output lineRuntimeWarning
lesson.py
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")
Output
RuntimeWarning
Estimate ready

The warning is recorded and the following statement still runs. Python warning filters control what happens to the warning.

Advertisements

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.

GivenWarning message “Wait estimated”
Worked resultWait estimated

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.

GivenWarning message “Room pending”
Worked resultRoom pending

What to watch for

Other languages use different severity categories. A warning should give the caller enough context to decide whether to continue.

Documentation for warnings.warn