Skip to content

Generate an optional error if __init__ has no annotation but class has annotationsΒ #15126

Open
@JukkaL

Description

@JukkaL

If __init__ has no annotation, it's likely that some attributes have implicit Any types, which seriously compromises type checking. This is a common mistake. Example where this is a problem:

class C:
    def __init__(self):
        self.a = []  # Inferred type for 'a' is Any, since no annotation

    def method(self) -> str:
        return self.a  # No error, since Any is compatible with str

Add an optional check to generate an error if __init__ has no type annotation but some attribute or method defined in the class body has a type annotation. The check would be enabled using --enable-error-code <code>.

Only look at definitions within the class body and ignore inherited __init__ and other inherited members.

This can be a little tricky to support in the daemon, since we'll need to add a dependency from every attribute to __init__ when the error code is enabled, if __init__ has no annotation (assuming this property is checked as part of checking __init__), and we need to keep track of whether each attribute has an annotation or not -- I'm not sure if the daemon keeps track of this or not.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions