Skip to content
Search

Python:@overrides

lastmod 2025-02-11created 2021-07-267 edits

overrides package

A decorator to automatically detect mismatch when overriding a method.

$ pip install overrides

Usage:

from overrides import overrides

class SuperClass:

    def foo(self):
        """This docstring will be inherited by any method that overrides this!"""
        return 1

    def bar(self, x) -> str:
        return x

class SubClass(SuperClass):

    @overrides
    def foo(self):
        return 2

    @overrides
    def bar(self, y) -> int: # Raises, because the signature is not compatible.
        return y

Fake decorator

If you don't want to include it as a required package, use the following decorator as a fake object:

# -*- coding: utf-8 -*-

from functools import wraps
from types import FunctionType
from typing import Callable, TypeVar, Union

_WrappedMethod = TypeVar("_WrappedMethod", bound=Union[FunctionType, Callable])
_DecoratorMethod = Callable[[_WrappedMethod], _WrappedMethod]


def _fake_override(func) -> Union[_DecoratorMethod, _WrappedMethod]:
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper


try:
    from overrides import override
except ImportError:
    override = _fake_override  # type: ignore[assignment]

Used in cvlayer.

Usage with @classmethod / @staticmethod

Put @classmethod and @staticmethod in front of @overrides. Other decorators don't seem to matter. Note that when several decorators are attached, their functionality is applied in order starting from the frontmost decorator.

class ChildClass(SuperClass):
    def __init__(self):
        pass

    @staticmethod
    @overrides
    def foo_function(x):
        print(f"Foo child function.{x}")
        return

See also

author Zer0 sitemap