8000 No warning for uninitialised instance variable when using instance variable annotation · Issue #4206 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content
No warning for uninitialised instance variable when using instance variable annotation #4206
Closed
@ned

Description

@ned

If you intend to initialise an instance variable in __init__ but forget to do so, mypy won't warn if PEP 526 style instance variable annotation is used. For example, the following code emits a runtime warning but no warning from mypy. Tested on mypy version 0.540.

class MyClass:
    my_attr: str
    def __init__(self, my_attr: str) -> None:
        pass
        # missing line: self.my_attr = my_attr

x = MyClass("grapefruit")
s: str = x.my_attr
#          ^ AttributeError at runtime

However, if the instance variable annotation is removed, mypy does warn.

class MyClass:
    def __init__(self, my_attr: str) -> None:
        pass
        # missing line: self.my_attr = my_attr

x = MyClass("grapefruit")
s: str = x.my_attr

From PEP 526 (emphasis mine):

In particular, the value-less notation a: int allows one to annotate instance variables that should be initialized in __init__ or __new__.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0