Python — Constant conventions and typing.Final
Python uses uppercase names to signal constants by convention. The Final annotation lets a static type checker detect attempts to reassign an annotated name.
A simple example
Use a fixed value
- Start with Unit is 3
- Do this Multiply by 2
- Result 6
UNIT = 3
print(2 * UNIT)
6
Name a fixed scheduling interval
Express a 30-minute slot in terms of a 15-minute base interval. Keep the slot count separate so different bookings can reuse the same rule. The interpreter does not enforce Final at runtime. It also does not freeze a mutable object held by the name. Whole-number intervals are immutable int values.
The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.
Run the example
Use Python 3.9 or later. Run these commands from the directory containing the example.
python3 lesson.py
from typing import Final
BASE_MINUTES: Final = 15
SLOT_MINUTES: Final = 2 * BASE_MINUTES
booked_slots = 3
print(f"{booked_slots * SLOT_MINUTES} minutes")
90 minutes
Two base intervals make each slot 30 minutes. A booking of three slots lasts 90 minutes.
Try it yourself
If the base interval changes to 10 minutes, how long is the same three-slot booking?
Check your answer
Each slot now lasts 20 minutes, so the booking lasts 60 minutes.