Final classes
You can apply the typing_extensions.final
decorator to a class to indicateto mypy that it should not be subclassed:
- from typing_extensions import final
- @final
- class Leaf:
- ...
- class MyLeaf(Leaf): # Error: Leaf can't be subclassed
- ...
The decorator acts as a declaration for mypy (and as documentation forhumans), but it doesn’t actually prevent subclassing at runtime.
Here are some situations where using a final class may be useful:
- A class wasn’t designed to be subclassed. Perhaps subclassing would notwork as expected, or subclassing would be error-prone.
- Subclassing would make code harder to understand or maintain.For example, you may want to prevent unnecessarily tight coupling betweenbase classes and subclasses.
- You want to retain the freedom to arbitrarily change the class implementationin the future, and these changes might break subclasses.
An abstract class that defines at least one abstract method orproperty and has @final
decorator will generate an error frommypy, since those attributes could never be implemented.
- from abc import ABCMeta, abstractmethod
- from typing_extensions import final
- @final
- class A(metaclass=ABCMeta): # error: Final class A has abstract attributes "f"
- @abstractmethod
- def f(self, x: int) -> None: pass