Skip to content

Python:@overrides

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

필수 패키지로 포함시키고 싶지 않을 경우 다음의 Decorator 를 Fake 객체로 사용하자:

# -*- 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]

cvlayer 에서 사용했다.

Usage with @classmethod / @staticmethod

@classmethod, @staticmethod 는 @overrides 앞에다 붙여주면 된다. 다른 데코레이터들은 따로 상관이 없는 듯 하다. 참고로 여러 데코레이터가 붙어 있는 경우에는 맨 앞의 데코레이터부터 순차적으로 기능이 적용된다.

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

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

See also