Final methods

Like with attributes, sometimes it is useful to protect a method fromoverriding. You can use the typing_extensions.finaldecorator for this purpose:

  1. from typing_extensions import final
  2.  
  3. class Base:
  4. @final
  5. def common_name(self) -> None:
  6. ...
  7.  
  8. class Derived(Base):
  9. def common_name(self) -> None: # Error: cannot override a final method
  10. ...

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):

  1. from typing import Any, overload
  2.  
  3. class Base:
  4. @overload
  5. def method(self) -> None: ...
  6. @overload
  7. def method(self, arg: int) -> int: ...
  8. @final
  9. def method(self, x=None):
  10. ...