From 898969c40237902050278c20a19b90ba98ef790f Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 27 Feb 2021 20:45:36 +0100 Subject: [PATCH] Don't transform dataclass ClassVars --- ChangeLog | 3 +++ astroid/brain/brain_dataclasses.py | 12 ++++++++++++ tests/unittest_brain.py | 12 ++++++++++++ 3 files changed, 27 insertions(+) diff --git a/ChangeLog b/ChangeLog index 519fa249f3..c30d7477c7 100644 --- a/ChangeLog +++ b/ChangeLog @@ -11,6 +11,9 @@ Release Date: TBA Closes #895 #899 +* Don't transform dataclass ClassVars + + What's New in astroid 2.5? ============================ Release Date: 2021-02-15 diff --git a/astroid/brain/brain_dataclasses.py b/astroid/brain/brain_dataclasses.py index 7a25e0c636..cbc83830e3 100644 --- a/astroid/brain/brain_dataclasses.py +++ b/astroid/brain/brain_dataclasses.py @@ -30,6 +30,18 @@ def dataclass_transform(node): if not isinstance(assign_node, (astroid.AnnAssign, astroid.Assign)): continue + if ( + isinstance(assign_node, astroid.AnnAssign) + and isinstance(assign_node.annotation, astroid.Subscript) + and ( + isinstance(assign_node.annotation.value, astroid.Name) + and assign_node.annotation.value.name == "ClassVar" + or isinstance(assign_node.annotation.value, astroid.Attribute) + and assign_node.annotation.value.attrname == "ClassVar" + ) + ): + continue + targets = ( assign_node.targets if hasattr(assign_node, "targets") diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py index dc3f25d430..b5d96c970f 100644 --- a/tests/unittest_brain.py +++ b/tests/unittest_brain.py @@ -2092,6 +2092,8 @@ def test_dataclasses(): code = """ import dataclasses from dataclasses import dataclass + import typing + from typing import ClassVar @dataclass class InventoryItem: @@ -2101,6 +2103,8 @@ class InventoryItem: @dataclasses.dataclass class Other: name: str + CONST_1: ClassVar[int] = 42 + CONST_2: typing.ClassVar[int] = 42 """ module = astroid.parse(code) @@ -2119,6 +2123,14 @@ class Other: 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",