Python's final qualifier
Python (>=3.8) tip:
You can use the
finaldecorator to declare that a:
- Method should not be overridden
- Class should not be subclassed
You can also use the
Finalannotation to declare that a variable or attribute should not be reassigned, redefined, or overridden. It can be used as indicator to another developer that the given variable should be treated as a constant:
from typing import Final _PI: Final = 3.14
A static type check will report an error when it's violated.
from typing import Final, final # example 1 @final class Cat: @final def meow(self): return "Meow" class WildCat(Cat): def meow(self): return "Grrr" # mypy cat.py # error: Cannot inherit from final class "Cat" # example 2 class Foo: @final def bar(self): return "baz" def foobar(): return "foobar" new = Foo() new.bar = foobar # mypy foo.py # error: Cannot assign to final attribute "bar" # example 3 favorite_color: Final[str] = "red" favorite_color = "blue" # mypy foo.py # error: Cannot assign to final name "favorite_color"