Overrides Library

7.7.0 · active · verified Sat Mar 28

The `overrides` library (v7.7.0) provides a Python decorator `@override` to ensure that a method in a subclass correctly overrides a method from its superclass. It also includes `EnforceOverrides` for metaclass-level checks and `@final` to prevent methods from being overridden. The library focuses on improving the safety and experience of creating class hierarchies by catching common errors at class creation time, such as signature mismatches or accidental non-overrides. It has a regular release cadence, with several minor and patch releases in the past year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `@override` decorator with the `EnforceOverrides` metaclass. The `Animal` class defines methods, and `Dog` subclasses it, using `@override` to explicitly mark overridden methods. If `EnforceOverrides` is used, methods intended to override a superclass method *must* use the `@override` decorator, otherwise a `TypeError` will be raised at class creation time. The library also automatically copies docstrings from the overridden method.

from overrides import override, EnforceOverrides

class Animal(EnforceOverrides):
    def make_sound(self) -> str:
        raise NotImplementedError

    def eat(self) -> str:
        return "Eating generic food"

class Dog(Animal):
    @override
    def make_sound(self) -> str:
        return "Woof!"
    
    # No @override needed if not overriding a method, or if EnforceOverrides is not used.
    def fetch(self) -> str:
        return "Fetching the ball"

# Example of usage
dog = Dog()
print(dog.make_sound())
print(dog.eat())

# This would raise TypeError if @override was missing on make_sound and EnforceOverrides was used.
# class Cat(Animal):
#     def make_sound(self) -> str: # Missing @override, would fail with EnforceOverrides
#         return "Meow!"

view raw JSON →