typing.Final - A constant reference to a non-constant object?

If you encounter the term Final, do you perceive it as indicating a constant object or a constant reference to a non-constant object?

In my scenario, I have a variable named registry, which is a mapping of string keys to specialized objects.

registry: Final[dict[str, MyObject]] = {}

Now, the registry variable is labeled as Final. Can the objects stored in the registry change?

Based on how Python handles tuples, I believe that Final denotes a constant reference to a non-constant object, i.e., I can add new MyObjects to the registry. Is this correct?

Other programming languages use different approaches. For instance, Dart features both final and const keywords. In Dart, final implies that the variable registry cannot be re-assigned to another object, while const signifies that the referenced object itself cannot be modified.

Does Python offer a mechanism distinguish between these two scenarios?

It’s a constant reference to an object, which may or may not be mutable.

Currently we don’t have a mutability type modifier, so you will either have to use a Protocol to restrict the available actions on the object so that it cannot be mutated (e.g. use Mapping instead of dict in the annotation) or use a type that is immutable to begin with, such as types.MappingProxyType.

2 Likes