Course contentsShow
← Python
Lesson 576 of 1,0609. Type Safety and Code QualityFree lesson

Using Final Bindings to Prevent Unintended Variable Reassignment

Apply the Final type hint to indicate that a variable or attribute should not be reassigned, acknowledging that it does not enforce runtime immutability.

In this lesson, you will learn how to use the Final type hint to communicate your intent to other developers and static type checkers that a variable should remain unchanged after its initial assignment.

Communicating Intent with Final

In professional software development, one of the most common sources of bugs is the accidental reassignment of a variable that was intended to be a constant. While Python does not natively prevent you from changing a variable's value at runtime, the typing module provides the Final qualifier. When you use Final, you are telling your static type checker (like Mypy or Pyright) that this name is "locked" to its initial value.

Consider this example:

from typing import Final

# This is a configuration constant that should not change
TIMEOUT_SECONDS: Final[int] = 30

# Later in the code, if you accidentally do this:
TIMEOUT_SECONDS = 60  # Your type checker will flag this as an error!

Important Distinctions

It is crucial to understand that Final is a tool for static analysis, not a runtime lock. If you run the code above, Python will not stop you from changing TIMEOUT_SECONDS to 60 at runtime. The language itself remains dynamic. However, by using Final, you enable your tools to catch potential logic errors before they ever reach production.

Furthermore, Final does not necessarily mean the object itself is immutable. If you assign a list to a Final variable, the variable name cannot be rebound to a different list, but the contents of that list (e.g., appending an item) can still be modified. Think of Final as a promise you make to your codebase: "This variable name is dedicated to this specific value for the duration of its lifecycle."

By using Final, you turn your code into a self-documenting contract, ensuring that your team understands exactly which values are intended to be fixed constants versus which ones are meant to evolve over time.

Key Takeaway: The Final type hint signals to static type checkers that a variable must not be reassigned, providing a safety net against logic errors without altering Python’s runtime behavior.