Task: Experiment with "override" and the new mypy explicit-override feature
MVrachev opened this issue · 0 comments
MVrachev commented
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
override
clearly separates which of the class methods are overriding the father class methods and which are unique to the child classoverride
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:
...
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.