diff options
| author | David Liu <david@cs.toronto.edu> | 2021-08-16 06:47:26 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-08-16 12:47:26 +0200 |
| commit | bd8818dffe7f0495c2a0c8c2efbd64ea3c984d98 (patch) | |
| tree | d9f5e6a09616ae11912a919d4bb51502ce3d4d94 | |
| parent | 162b4a7b744fdf4447e75173136221d5bf466102 (diff) | |
| download | astroid-git-bd8818dffe7f0495c2a0c8c2efbd64ea3c984d98.tar.gz | |
Add inference tips for dataclass attributes (#1126)
* Add inference tips for dataclass attributes
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
| -rw-r--r-- | ChangeLog | 9 | ||||
| -rw-r--r-- | astroid/brain/brain_dataclasses.py | 244 | ||||
| -rw-r--r-- | astroid/nodes/node_classes.py | 2 | ||||
| -rw-r--r-- | astroid/transforms.py | 3 | ||||
| -rw-r--r-- | tests/unittest_brain.py | 45 | ||||
| -rw-r--r-- | tests/unittest_brain_dataclasses.py | 237 |
6 files changed, 459 insertions, 81 deletions
@@ -15,10 +15,19 @@ Release date: TBA Closes PyCQA/pylint#2224 Closes PyCQA/pylint#2626 +* Add inference tips for dataclass attributes, including dataclasses.field calls. + Also add support for InitVar. + + Closes PyCQA/pylint#2600 + Closes PyCQA/pylint#2698 + Closes PyCQA/pylint#3405 + Closes PyCQA/pylint#3794 + * Adds a brain that deals with dynamic import of `IsolatedAsyncioTestCase` class of the `unittest` module. Closes PyCQA/pylint#4060 + What's New in astroid 2.6.7? ============================ Release date: TBA diff --git a/astroid/brain/brain_dataclasses.py b/astroid/brain/brain_dataclasses.py index cd87c183..f42c981c 100644 --- a/astroid/brain/brain_dataclasses.py +++ b/astroid/brain/brain_dataclasses.py @@ -3,67 +3,245 @@ """ Astroid hook for the dataclasses library """ +from typing import Generator, Tuple, Union + +from astroid import context, inference_tip +from astroid.builder import parse +from astroid.const import PY37_PLUS, PY39_PLUS +from astroid.exceptions import InferenceError from astroid.manager import AstroidManager from astroid.nodes.node_classes import ( AnnAssign, - Assign, + AssignName, Attribute, Call, Name, + NodeNG, Subscript, Unknown, ) -from astroid.nodes.scoped_nodes import ClassDef +from astroid.nodes.scoped_nodes import ClassDef, FunctionDef +from astroid.util import Uninferable -DATACLASSES_DECORATORS = frozenset(("dataclasses.dataclass", "dataclass")) +DATACLASSES_DECORATORS = frozenset(("dataclass",)) +FIELD_NAME = "field" +DATACLASS_MODULE = "dataclasses" def is_decorated_with_dataclass(node, decorator_names=DATACLASSES_DECORATORS): """Return True if a decorated node has a `dataclass` decorator applied.""" - if not node.decorators: + if not isinstance(node, ClassDef) or not node.decorators: return False + for decorator_attribute in node.decorators.nodes: if isinstance(decorator_attribute, Call): # decorator with arguments decorator_attribute = decorator_attribute.func - if decorator_attribute.as_string() in decorator_names: + + try: + inferred = next(decorator_attribute.infer()) + except (InferenceError, StopIteration): + continue + + if not isinstance(inferred, FunctionDef): + continue + + if ( + inferred.name in decorator_names + and inferred.root().name == DATACLASS_MODULE + ): return True + return False -def dataclass_transform(node): +def dataclass_transform(node: ClassDef) -> None: """Rewrite a dataclass to be easily understood by pylint""" for assign_node in node.body: - if not isinstance(assign_node, (AnnAssign, Assign)): + if not isinstance(assign_node, AnnAssign) or not isinstance( + assign_node.target, AssignName + ): continue - if ( - isinstance(assign_node, AnnAssign) - and isinstance(assign_node.annotation, Subscript) - and ( - isinstance(assign_node.annotation.value, Name) - and assign_node.annotation.value.name == "ClassVar" - or isinstance(assign_node.annotation.value, Attribute) - and assign_node.annotation.value.attrname == "ClassVar" - ) + if _is_class_var(assign_node.annotation) or _is_init_var( + assign_node.annotation ): continue - targets = ( - assign_node.targets - if hasattr(assign_node, "targets") - else [assign_node.target] + name = assign_node.target.name + + rhs_node = Unknown( + lineno=assign_node.lineno, + col_offset=assign_node.col_offset, + parent=assign_node, ) - for target in targets: - rhs_node = Unknown( - lineno=assign_node.lineno, - col_offset=assign_node.col_offset, - parent=assign_node, - ) - node.instance_attrs[target.name] = [rhs_node] - node.locals[target.name] = [rhs_node] - - -AstroidManager().register_transform( - ClassDef, dataclass_transform, is_decorated_with_dataclass -) + rhs_node = AstroidManager().visit_transforms(rhs_node) + node.instance_attrs[name] = [rhs_node] + + +def infer_dataclass_attribute( + node: Unknown, ctx: context.InferenceContext = None +) -> Generator: + """Inference tip for an Unknown node that was dynamically generated to + represent a dataclass attribute. + + In the case that a default value is provided, that is inferred first. + Then, an Instance of the annotated class is yielded. + """ + assign = node.parent + if not isinstance(assign, AnnAssign): + yield Uninferable + return + + annotation, value = assign.annotation, assign.value + if value is not None: + yield from value.infer(context=ctx) + if annotation is not None: + klass = None + try: + klass = next(annotation.infer()) + except (InferenceError, StopIteration): + yield Uninferable + + if not isinstance(klass, ClassDef): + yield Uninferable + else: + yield klass.instantiate_class() + else: + yield Uninferable + + +def infer_dataclass_field_call( + node: AssignName, ctx: context.InferenceContext = None +) -> Generator: + """Inference tip for dataclass field calls.""" + field_call = node.parent.value + result = _get_field_default(field_call) + if result is None: + yield Uninferable + else: + default_type, default = result + if default_type == "default": + yield from default.infer(context=ctx) + else: + new_call = parse(default.as_string()).body[0].value + new_call.parent = field_call.parent + yield from new_call.infer(context=ctx) + + +def _looks_like_dataclass_attribute(node: Unknown) -> bool: + """Return True if node was dynamically generated as the child of an AnnAssign + statement. + """ + parent = node.parent + scope = parent.scope() + return ( + isinstance(parent, AnnAssign) + and isinstance(scope, ClassDef) + and is_decorated_with_dataclass(scope) + ) + + +def _looks_like_dataclass_field_call(node: Call, check_scope: bool = True) -> bool: + """Return True if node is calling dataclasses field or Field + from an AnnAssign statement directly in the body of a ClassDef. + + If check_scope is False, skips checking the statement and body. + """ + if check_scope: + stmt = node.statement() + scope = stmt.scope() + if not ( + isinstance(stmt, AnnAssign) + and isinstance(scope, ClassDef) + and is_decorated_with_dataclass(scope) + ): + return False + + try: + inferred = next(node.func.infer()) + except (InferenceError, StopIteration): + return False + + if not isinstance(inferred, FunctionDef): + return False + + return inferred.name == FIELD_NAME and inferred.root().name == DATACLASS_MODULE + + +def _get_field_default(field_call: Call) -> Union[Tuple[str, NodeNG], None]: + """Return a the default value of a field call, and the corresponding keyword argument name. + + field(default=...) results in the ... node + field(default_factory=...) results in a Call node with func ... and no arguments + + If neither or both arguments are present, return None instead. + """ + default, default_factory = None, None + for keyword in field_call.keywords: + if keyword.arg == "default": + default = keyword.value + elif keyword.arg == "default_factory": + default_factory = keyword.value + + if default is not None and default_factory is None: + return "default", default + + if default is None and default_factory is not None: + new_call = Call( + lineno=field_call.lineno, + col_offset=field_call.col_offset, + parent=field_call.parent, + ) + new_call.postinit(func=default_factory) + return "default_factory", new_call + + return None + + +def _is_class_var(node: NodeNG) -> bool: + """Return True if node is a ClassVar, with or without subscripting.""" + if PY39_PLUS: + try: + inferred = next(node.infer()) + except (InferenceError, StopIteration): + return False + + return getattr(inferred, "name", "") == "ClassVar" + + # Before Python 3.9, inference returns typing._SpecialForm instead of ClassVar. + # Our backup is to inspect the node's structure. + return isinstance(node, Subscript) and ( + isinstance(node.value, Name) + and node.value.name == "ClassVar" + or isinstance(node.value, Attribute) + and node.value.attrname == "ClassVar" + ) + + +def _is_init_var(node: NodeNG) -> bool: + """Return True if node is an InitVar, with or without subscripting.""" + try: + inferred = next(node.infer()) + except (InferenceError, StopIteration): + return False + + return getattr(inferred, "name", "") == "InitVar" + + +if PY37_PLUS: + AstroidManager().register_transform( + ClassDef, dataclass_transform, is_decorated_with_dataclass + ) + + AstroidManager().register_transform( + Call, + inference_tip(infer_dataclass_field_call, raise_on_overwrite=True), + _looks_like_dataclass_field_call, + ) + + AstroidManager().register_transform( + Unknown, + inference_tip(infer_dataclass_attribute, raise_on_overwrite=True), + _looks_like_dataclass_attribute, + ) diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py index 3c7cf9fe..0c46d11d 100644 --- a/astroid/nodes/node_classes.py +++ b/astroid/nodes/node_classes.py @@ -4158,7 +4158,7 @@ class Unknown(mixins.AssignTypeMixin, NodeNG): def qname(self): return "Unknown" - def infer(self, context=None, **kwargs): + def _infer(self, context=None, **kwargs): """Inference on an Unknown node immediately terminates.""" yield util.Uninferable diff --git a/astroid/transforms.py b/astroid/transforms.py index 2bab4fac..8911f2a3 100644 --- a/astroid/transforms.py +++ b/astroid/transforms.py @@ -92,5 +92,4 @@ class TransformVisitor: Only the nodes which have transforms registered will actually be replaced or changed. """ - module.body = [self._visit(child) for child in module.body] - return self._transform(module) + return self._visit(module) diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py index 4cbed876..1437fab4 100644 --- a/tests/unittest_brain.py +++ b/tests/unittest_brain.py @@ -2965,51 +2965,6 @@ def test_crypt_brain(): assert attr in module -@pytest.mark.skipif(not PY37_PLUS, reason="Dataclasses were added in 3.7") -def test_dataclasses(): - code = """ - import dataclasses - from dataclasses import dataclass - import typing - from typing import ClassVar - - @dataclass - class InventoryItem: - name: str - quantity_on_hand: int = 0 - - @dataclasses.dataclass - class Other: - name: str - CONST_1: ClassVar[int] = 42 - CONST_2: typing.ClassVar[int] = 42 - """ - - module = astroid.parse(code) - first = module["InventoryItem"] - second = module["Other"] - - name = first.getattr("name") - assert len(name) == 1 - assert isinstance(name[0], astroid.Unknown) - - quantity_on_hand = first.getattr("quantity_on_hand") - assert len(quantity_on_hand) == 1 - assert isinstance(quantity_on_hand[0], astroid.Unknown) - - name = second.getattr("name") - assert len(name) == 1 - assert isinstance(name[0], astroid.Unknown) - - const_1 = second.getattr("CONST_1") - assert len(const_1) == 1 - assert isinstance(const_1[0], astroid.AssignName) - - const_2 = second.getattr("CONST_2") - assert len(const_2) == 1 - assert isinstance(const_2[0], astroid.AssignName) - - @pytest.mark.parametrize( "code,expected_class,expected_value", [ diff --git a/tests/unittest_brain_dataclasses.py b/tests/unittest_brain_dataclasses.py new file mode 100644 index 00000000..f7b08747 --- /dev/null +++ b/tests/unittest_brain_dataclasses.py @@ -0,0 +1,237 @@ +import pytest + +import astroid +from astroid import bases, nodes +from astroid.const import PY37_PLUS +from astroid.exceptions import InferenceError + +if not PY37_PLUS: + pytest.skip("Dataclasses were added in 3.7", allow_module_level=True) + + +def test_inference_attribute_no_default(): + """Test inference of dataclass attribute with no default. + + Note that the argument to the constructor is ignored by the inference. + """ + klass, instance = astroid.extract_node( + """ + from dataclasses import dataclass + + @dataclass + class A: + name: str + + A.name #@ + A('hi').name #@ + """ + ) + with pytest.raises(InferenceError): + klass.inferred() + + inferred = instance.inferred() + assert len(inferred) == 1 + assert isinstance(inferred[0], bases.Instance) + assert inferred[0].name == "str" + + +def test_inference_non_field_default(): + """Test inference of dataclass attribute with a non-field default.""" + klass, instance = astroid.extract_node( + """ + from dataclasses import dataclass + + @dataclass + class A: + name: str = 'hi' + + A.name #@ + A().name #@ + """ + ) + inferred = klass.inferred() + assert len(inferred) == 1 + assert isinstance(inferred[0], nodes.Const) + assert inferred[0].value == "hi" + + inferred = instance.inferred() + assert len(inferred) == 2 + assert isinstance(inferred[0], nodes.Const) + assert inferred[0].value == "hi" + + assert isinstance(inferred[1], bases.Instance) + assert inferred[1].name == "str" + + +def test_inference_field_default(): + """Test inference of dataclass attribute with a field call default + (default keyword argument given).""" + klass, instance = astroid.extract_node( + """ + from dataclasses import dataclass, field + + @dataclass + class A: + name: str = field(default='hi') + + A.name #@ + A().name #@ + """ + ) + inferred = klass.inferred() + assert len(inferred) == 1 + assert isinstance(inferred[0], nodes.Const) + assert inferred[0].value == "hi" + + inferred = instance.inferred() + assert len(inferred) == 2 + assert isinstance(inferred[0], nodes.Const) + assert inferred[0].value == "hi" + + assert isinstance(inferred[1], bases.Instance) + assert inferred[1].name == "str" + + +def test_inference_field_default_factory(): + """Test inference of dataclass attribute with a field call default + (default_factory keyword argument given).""" + klass, instance = astroid.extract_node( + """ + from dataclasses import dataclass, field + + @dataclass + class A: + name: list = field(default_factory=list) + + A.name #@ + A().name #@ + """ + ) + inferred = klass.inferred() + assert len(inferred) == 1 + assert isinstance(inferred[0], nodes.List) + assert inferred[0].elts == [] + + inferred = instance.inferred() + assert len(inferred) == 2 + assert isinstance(inferred[0], nodes.List) + assert inferred[0].elts == [] + + assert isinstance(inferred[1], bases.Instance) + assert inferred[1].name == "list" + + +def test_inference_method(): + """Test inference of dataclass attribute within a method, + with a default_factory field. + + Based on https://github.com/PyCQA/pylint/issues/2600 + """ + node = astroid.extract_node( + """ + from typing import Dict + from dataclasses import dataclass, field + + @dataclass + class TestClass: + foo: str + bar: str + baz_dict: Dict[str, str] = field(default_factory=dict) + + def some_func(self) -> None: + f = self.baz_dict.items #@ + for key, value in f(): + print(key) + print(value) + """ + ) + inferred = next(node.value.infer()) + assert isinstance(inferred, bases.BoundMethod) + + +def test_inference_no_annotation(): + """Test that class variables without type annotations are not + turned into instance attributes. + """ + class_def, klass, instance = astroid.extract_node( + """ + from dataclasses import dataclass + + @dataclass + class A: + name = 'hi' + + A #@ + A.name #@ + A().name #@ + """ + ) + inferred = next(class_def.infer()) + assert isinstance(inferred, nodes.ClassDef) + assert inferred.instance_attrs == {} + + # Both the class and instance can still access the attribute + for node in (klass, instance): + inferred = node.inferred() + assert len(inferred) == 1 + assert isinstance(inferred[0], nodes.Const) + assert inferred[0].value == "hi" + + +def test_inference_class_var(): + """Test that class variables with a ClassVar type annotations are not + turned into instance attributes. + """ + class_def, klass, instance = astroid.extract_node( + """ + from dataclasses import dataclass + from typing import ClassVar + + @dataclass + class A: + name: ClassVar[str] = 'hi' + + A #@ + A.name #@ + A().name #@ + """ + ) + inferred = next(class_def.infer()) + assert isinstance(inferred, nodes.ClassDef) + assert inferred.instance_attrs == {} + + # Both the class and instance can still access the attribute + for node in (klass, instance): + inferred = node.inferred() + assert len(inferred) == 1 + assert isinstance(inferred[0], nodes.Const) + assert inferred[0].value == "hi" + + +def test_inference_init_var(): + """Test that class variables with InitVar type annotations are not + turned into instance attributes. + """ + class_def, klass, instance = astroid.extract_node( + """ + from dataclasses import dataclass, InitVar + + @dataclass + class A: + name: InitVar[str] = 'hi' + + A #@ + A.name #@ + A().name #@ + """ + ) + inferred = next(class_def.infer()) + assert isinstance(inferred, nodes.ClassDef) + assert inferred.instance_attrs == {} + + # Both the class and instance can still access the attribute + for node in (klass, instance): + inferred = node.inferred() + assert len(inferred) == 1 + assert isinstance(inferred[0], nodes.Const) + assert inferred[0].value == "hi" |
