Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make override decorator mandatory?

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: 
        ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

(playground)

# 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: ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading