diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 31c47ac77a..bd61830403 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -552,3 +552,5 @@ contributors: * Jaehoon Hwang (jaehoonhwang): contributor * Samuel Forestier: contributor + +* James DesLauriers: contributor diff --git a/ChangeLog b/ChangeLog index e4f6270d35..10af89334e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -40,6 +40,10 @@ Release date: TBA * Added ``using-f-string-in-unsupported-version`` checker. Issued when ``py-version`` is set to a version that does not support f-strings (< 3.6) +* Properly emit ``duplicate-key`` when Enum members are duplicate dictionary keys + + Closes #5150 + * Use ``py-version`` setting for alternative union syntax check (PEP 604), instead of the Python interpreter version. diff --git a/pylint/checkers/base.py b/pylint/checkers/base.py index 124881b770..36b50186ba 100644 --- a/pylint/checkers/base.py +++ b/pylint/checkers/base.py @@ -1452,9 +1452,13 @@ def visit_dict(self, node: nodes.Dict) -> None: for k, _ in node.items: if isinstance(k, nodes.Const): key = k.value - if key in keys: - self.add_message("duplicate-key", node=node, args=key) - keys.add(key) + elif isinstance(k, nodes.Attribute): + key = k.as_string() + else: + continue + if key in keys: + self.add_message("duplicate-key", node=node, args=key) + keys.add(key) def visit_tryfinally(self, node: nodes.TryFinally) -> None: """update try...finally flag""" diff --git a/tests/functional/d/duplicate_dict_literal_key.py b/tests/functional/d/duplicate_dict_literal_key.py index 6d359ff0a9..82e98d23ec 100644 --- a/tests/functional/d/duplicate_dict_literal_key.py +++ b/tests/functional/d/duplicate_dict_literal_key.py @@ -1,11 +1,25 @@ """Check multiple key definition""" # pylint: disable=pointless-statement, redundant-u-string-prefix +from enum import Enum + + +class MyEnum(Enum): + """ Sample Enum for testing duplicate keys""" + KEY = "key" + + + correct_dict = { 'tea': 'for two', 'two': 'for tea', } +wrong_with_enum = { # [duplicate-key] + MyEnum.KEY: "value 1", + MyEnum.KEY: "value 2", +} + wrong_dict = { # [duplicate-key] 'tea': 'for two', 'two': 'for tea', diff --git a/tests/functional/d/duplicate_dict_literal_key.txt b/tests/functional/d/duplicate_dict_literal_key.txt index 756f158188..83941b9889 100644 --- a/tests/functional/d/duplicate_dict_literal_key.txt +++ b/tests/functional/d/duplicate_dict_literal_key.txt @@ -1,3 +1,4 @@ -duplicate-key:9:13::Duplicate key 'tea' in dictionary -duplicate-key:16:0::Duplicate key 1 in dictionary -duplicate-key:17:0::Duplicate key 1.0 in dictionary +duplicate-key:18:18::Duplicate key 'MyEnum.KEY' in dictionary:HIGH +duplicate-key:23:13::Duplicate key 'tea' in dictionary:HIGH +duplicate-key:30:0::Duplicate key 1 in dictionary:HIGH +duplicate-key:31:0::Duplicate key 1.0 in dictionary:HIGH