Skip to content

Fix crash when a dataclass with a no init InitVar is inherited #7390

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,12 @@ def transform(self) -> None:
# Some definitions are not ready, defer() should be already called.
return
for attr in attributes:
if info[attr.name].type is None:
node = info.get(attr.name)
if node is None:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var and not attr.is_in_init
continue
if node.type is None:
ctx.api.defer()
return
decorator_arguments = {
Expand Down Expand Up @@ -184,7 +189,11 @@ def reset_init_only_vars(self, info: TypeInfo, attributes: List[DataclassAttribu
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
if attr.is_init_var:
del info.names[attr.name]
if attr.name in info.names:
del info.names[attr.name]
else:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var and not attr.is_in_init
for stmt in info.defn.defs.body:
if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
lvalue = stmt.lvalues[0]
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,22 @@ app.database_name # E: "Application" has no attribute "database_name"
class Yes: ...
[builtins fixtures/list.pyi]

[case testDataclassesNoInitInitVarInheritance]
from dataclasses import dataclass, field, InitVar

@dataclass
class Super:
foo: InitVar = field(init=False)

@dataclass
class Sub(Super):
bar: int

sub = Sub(5)
sub.foo # E: "Sub" has no attribute "foo"
sub.bar
[builtins fixtures/bool.pyi]

[case testDataclassFactory]
from typing import Type, TypeVar
from dataclasses import dataclass
Expand Down