Skip to content

Signature inference for special methods #20647

@user202729

Description

@user202729

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions