Strict Immutability with Final and @final
`typing.Final` declares constants that must not be reassigned. The `@final` decorator prevents classes from being subclassed or methods from being overridden 🔒.
from typing import Final, final
MAX_CONNECTIONS: Final = 100
# MAX_CONNECTIONS = 200 # Flagged by Mypy! 🛑
@final
class CoreEngine:
"""Cannot be inherited!"""
pass
print(f"Constant locked: {MAX_CONNECTIONS} 🔒")
# 94. Strict Immutability with Final and @final `typing.Final` declares constants that must not be reassigned. The `@final` decorator prevents classes from being subclassed or methods from being overridden 🔒. ```python from typing import Final, final MAX_CONNECTIONS: Final = 100 # MAX_CONNECTIONS = 200 # Flagged by Mypy! 🛑 @final class CoreEngine: """Cannot be inherited!""" pass print(f"Constant locked: {MAX_CONNECTIONS} 🔒") ``` Like all typing hints, `Final` is statically verified. Python won't raise an error at runtime on reassignment, but linters will fail CI/CD builds! 🔒 --- ### Question What does decorating a method with `@final` communicate to type checkers? 🧠- [ ] a. Subclasses are prohibited from overriding this specific method 🔒 - [ ] b. The method can only be invoked once before being deleted - [ ] c. The method executes automatically upon program exit - [ ] d. The method runs exclusively in read-only RAM --- ### Challenge Import `Final` from `typing`. Declare `DATABASE_PORT: Final = 5432`. Print `DATABASE_PORT`. 🎯 <details> <summary>Solution</summary> ```python from typing import Final DATABASE_PORT: Final = 5432 print(DATABASE_PORT) ``` </details>