Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task: Experiment with "override" and the new mypy explicit-override feature #362

Open
MVrachev opened this issue Aug 16, 2023 · 0 comments

Comments

@MVrachev
Copy link
Member

MVrachev commented Aug 16, 2023

What is the task about?

For a while, the override annotation existed inside the typing module:
https://peps.python.org/pep-0698/

Use case:

from typing import override

class Parent:
    def foo(self) -> int:
        return 1

class Child(Parent):
    @override
    def foo(self) -> int:
        return 2

The override annotation will annotate that a specific class function in the Child class is overriding a father method.

This feature could be really useful if combined with the new mypy version 1.5 feature called explicit-override.
For reference: https://mypy-lang.blogspot.com/2023/08/mypy-15-released.html

Advantages

  1. override clearly separates which of the class methods are overriding the father class methods and which are unique to the child class
  2. override can be used to make sure that an implementor of an interface doesn't override a father class method by mistake:
    Example:
# mypy: enable-error-code="explicit-override"

from typing_extensions import override

class C:
    def foo(self) -> None: pass

class D(C):
    # Error: Method "foo" is not using @override but is 
    # overriding a method
    def foo(self) -> None:
        ...
  1. override can be used to identify that the child class methods aiming to override a father class method indeed do so and their types are correct:
from typing import override

class Parent:
    def foo(self) -> int:
        return 1

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

class Child(Parent):
    @override
    def foo(self) -> int:
        return 2

    @override
    def baz() -> int:  # Type check error: no matching signature in ancestor
        return 1

Disadvantages
Using @override will make the code more verbose.

Requirements feature

#365 - fixing before working on this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant