Python 3.8+typingterm
typing.final
decorators and markers
The @final decorator: the class must not be subclassed and the method must not be overridden. Only a type checker enforces it, not the interpreter.
Syntax
@final
class Leaf: ...
Do not confuse it with Final: typing.Final annotates a variable (MAX: Final = 10, 'do not reassign'), while @final decorates a class or a method. At runtime subclassing a @final class succeeds silently; only mypy or pyright report it. Since 3.11 the decorator sets __final__ = True, but that is an ordinary class attribute that subclasses inherit too, so getattr(Sub, '__final__') is True for a subclass as well — check vars(cls) instead.
Examples
# Python 3.11+
from typing import final
@final
class Leaf:
pass
class Other(Leaf): # mypy: Cannot inherit from final class
pass
print(Leaf.__final__, getattr(Other, '__final__', False)) # → True True — атрибут унаследован
print('__final__' in vars(Other)) # → False
from typing import final
class Base:
@final
def done(self) -> str:
return 'base'
class Sub(Base):
def done(self) -> str: # mypy: Cannot override final attribute
return 'sub'
print(Sub().done()) # → sub — интерпретатор не мешает
See also
Open in the full glossarydocs.python.orgReport an inaccuracy