Skip to content

Commit

Permalink
Fix crash on datafields (#1165)
Browse files Browse the repository at this point in the history
* Fix crash on datafields
Fixes the crash reported at pylint-dev/pylint#4963
Tests added there.

* Change to ``if not``

* Update astroid/brain/brain_dataclasses.py

* Add tests

* Update and merge test

* Use ``raise UseInferenceDefault``
  • Loading branch information
DanielNoord authored Sep 13, 2021
1 parent 741cd61 commit af0724b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
3 changes: 3 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ What's New in astroid 2.7.4?
============================
Release date: TBA

* Fixed bug in inference of dataclass field calls.

Closes PyCQA/pylint#4963


What's New in astroid 2.7.3?
Expand Down
12 changes: 10 additions & 2 deletions astroid/brain/brain_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,16 @@
from astroid import context, inference_tip
from astroid.builder import parse
from astroid.const import PY37_PLUS, PY39_PLUS
from astroid.exceptions import AstroidSyntaxError, InferenceError, MroError
from astroid.exceptions import (
AstroidSyntaxError,
InferenceError,
MroError,
UseInferenceDefault,
)
from astroid.manager import AstroidManager
from astroid.nodes.node_classes import (
AnnAssign,
Assign,
AssignName,
Attribute,
Call,
Expand Down Expand Up @@ -231,9 +237,11 @@ def infer_dataclass_attribute(


def infer_dataclass_field_call(
node: AssignName, ctx: context.InferenceContext = None
node: Call, ctx: Optional[context.InferenceContext] = None
) -> Generator:
"""Inference tip for dataclass field calls."""
if not isinstance(node.parent, (AnnAssign, Assign)):
raise UseInferenceDefault
field_call = node.parent.value
default_type, default = _get_field_default(field_call)
if not default_type:
Expand Down
18 changes: 18 additions & 0 deletions tests/unittest_brain_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,3 +643,21 @@ class A:
)
init = next(node.infer())
assert init._proxied.parent.name == "object"


@parametrize_module
def test_annotated_enclosed_field_call(module: str):
"""Test inference of dataclass attribute with a field call in another function call"""
node = astroid.extract_node(
f"""
from {module} import dataclass, field
from typing import cast
@dataclass
class A:
attribute: int = cast(int, field(default_factory=dict))
"""
)
inferred = node.inferred()
assert len(inferred) == 1 and isinstance(inferred[0], nodes.ClassDef)
assert "attribute" in inferred[0].instance_attrs

0 comments on commit af0724b

Please sign in to comment.