-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
We have the following
class A:
def __contains__(self, x: int) -> bool:
return None # incompatible return value type
class B:
def __contains__(self, x: int):
return None # no error?
Currently, in order to type-check the return type of special methods such as __contains__ or __len__, it is necessary to explicitly type-annotate them, even though it ought to be "obvious" i.e. bool and int respectively.
Suggestion: Add a configuration like automatic-signature-special-methods that will behave as if every special methods are annotated with the correct types. Together with check-untyped-defs (or maybe a lighter configuration like check-untyped-special-methods)
Note that currently Python official documentation has this statement, regarding type annotation for special methods (https://typing.python.org/en/latest/spec/annotations.html)
(Note that the return type of init ought to be annotated with -> None. The reason for this is subtle. If init assumed a return annotation of -> None, would that mean that an argument-less, un-annotated init method should still be type-checked? Rather than leaving this ambiguous or introducing an exception to the exception, we simply say that init ought to have a return annotation; the default behavior is thus the same as for other methods.)
The advantages are
- Avoid mistakes in annotating these methods Do we want "obvious" type annotations for e.g. __init__, __contains__, etc.? sagemath/sage#41500
- Less code to read, less mental overhead