Final classes

You can apply the typing_extensions.final decorator to a class to indicateto mypy that it should not be subclassed:

  1. from typing_extensions import final
  2.  
  3. @final
  4. class Leaf:
  5. ...
  6.  
  7. class MyLeaf(Leaf): # Error: Leaf can't be subclassed
  8. ...

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.

  1. from abc import ABCMeta, abstractmethod
  2. from typing_extensions import final
  3.  
  4. @final
  5. class A(metaclass=ABCMeta): # error: Final class A has abstract attributes "f"
  6. @abstractmethod
  7. def f(self, x: int) -> None: pass