Skip to content

Commit

Permalink
ensure dataclass init fn has the correct signature
Browse files Browse the repository at this point in the history
  • Loading branch information
tgallant committed Aug 2, 2021
1 parent bb67682 commit 77c7ca2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
15 changes: 12 additions & 3 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ def transform(self) -> None:
add_method(
ctx,
'__init__',
args=[attr.to_argument() for attr in attributes if attr.is_in_init],
args=[attr.to_argument() for attr in attributes if attr.is_in_init
and not self._is_kw_only_type(attr.type)],
return_type=NoneType(),
)

Expand Down Expand Up @@ -257,8 +258,7 @@ def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
is_init_var = True
node.type = node_type.args[0]

if (isinstance(node_type, Instance) and
node_type.type.fullname == 'dataclasses._KW_ONLY_TYPE'):
if self._is_kw_only_type(node_type):
kw_only = True

has_field_call, field_args = _collect_field_args(stmt.rvalue)
Expand Down Expand Up @@ -395,6 +395,15 @@ def _propertize_callables(self, attributes: List[DataclassAttribute]) -> None:
var._fullname = info.fullname + '.' + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)

def _is_kw_only_type(self, node: Optional[Type]) -> bool:
"""Checks if the type of the node is the KW_ONLY sentinel value."""
if node is None:
return False
node_type = get_proper_type(node)
if not isinstance(node_type, Instance):
return False
return node_type.type.fullname == 'dataclasses._KW_ONLY_TYPE'


def dataclass_class_maker_callback(ctx: ClassDefContext) -> None:
"""Hooks into the class typechecking process to add support for dataclasses.
Expand Down
2 changes: 2 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,8 @@ class D(Base):
z: str
a: str = "a"

D("Hello", "World")

[builtins fixtures/list.pyi]

[case testDataclassesClassmethods]
Expand Down

0 comments on commit 77c7ca2

Please sign in to comment.