I came across new override decorator for Python 3.12 and it looks like an extremely good practice.
I’m wondering if there is a way to make it "mandatory" to use? Perhaps there is some way to configure mypy for it? Or at least configure linters to show warnings.
from typing import override
class Base:
def log_status(self) -> None:
...
class Sub(Base):
@override # I would like to make it mandatory while overriding a method
def log_status(self) -> None:
...
>Solution :
Mypy has a dedicated rule for this: explicit-override.
Put the following in your pyproject.toml to enable it:
[tool.mypy]
enable_error_code = "explicit-override"
This can also be used in mypy.ini and other kinds of configuration files Mypy reads, but that is left as an exercise for the reader.
Alternatively, you can pass --enable-error-code explicit-override to the command line tool or place a configuration comment in your file:
# mypy: enable-error-code=explicit-override
class Sub(Base):
# error: Method "..." is not using @override but is overriding a method in class "..."
def log_status(self) -> None: ...