Final methods
Like with attributes, sometimes it is useful to protect a method fromoverriding. You can use the typing_extensions.final
decorator for this purpose:
- from typing_extensions import final
- class Base:
- @final
- def common_name(self) -> None:
- ...
- class Derived(Base):
- def common_name(self) -> None: # Error: cannot override a final method
- ...
This @final
decorator can be used with instance methods, class methods,static methods, and properties.
For overloaded methods you should add @final
on the implementationto make it final (or on the first overload in stubs):
- from typing import Any, overload
- class Base:
- @overload
- def method(self) -> None: ...
- @overload
- def method(self, arg: int) -> int: ...
- @final
- def method(self, x=None):
- ...