ruff icon indicating copy to clipboard operation
ruff copied to clipboard

Rule for missing PEP 698 `@override` decorators?

Open guillp opened this issue 2 years ago • 5 comments

An idea for a new rule: checking that methods in subclasses that override methods from the parent are decorated with @override. This decorator is defined in PEP 698 and is meant to help both linters and developpers to recognize methods that are overriding methods from a parent class.

Example:


class A:
    def foo(self) -> None:
        print("foo from class A!")

class B(A):
    def foo(self) -> None:
        print("foo from class B!")

A rule would detect that the @override decorator is missing on B.foo() since it overrides A.foo().

Note that until python 3.12, override is only available from typing-extensions.

guillp avatar Aug 24 '23 08:08 guillp

TIL!

This sounds good to me as a great Python 3.12 milestone although I do not think it should be enabled by default.

zanieb avatar Aug 24 '23 20:08 zanieb

The challenge here is that we won’t be able to enforce this except for cases in which the parent class and subclass are defined in the same file (until we have multi-file analysis).

charliermarsh avatar Aug 24 '23 20:08 charliermarsh

Great point, it may not be worth prioritizing until then since there will be many false negatives

zanieb avatar Aug 24 '23 20:08 zanieb

There is also the inverse problem of having @override on a class without bases, or @overload on a function without the function without @overload.

JonathanPlasse avatar Sep 22 '23 11:09 JonathanPlasse

I found this thread while looking for the same. Are there any other linters that currently support this?

Asked also here:

  • https://github.com/mkorpela/overrides/issues/120

aaronsteers avatar Dec 21 '23 19:12 aaronsteers

Is this something that might be more appropriate for red-knot?

Edit: I see that it was tagged as type-inference by Micha, who is working on red-knot.

illusional avatar Jan 31 '25 17:01 illusional

up! 🫡 Is there is any work on this since then? We're also debating on how to properly define subclassed methods and having a rule about enforcing the usage of @override would be very appreciated!

folkvir avatar Oct 29 '25 10:10 folkvir