Closed
Description
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
Labels
No labels