Skip to content

Commit 9098c60

Browse files
Consider Enums when checking for duplicate dictionary keys (#5155)
* detect duplicate-key for enum members Co-authored-by: Pierre Sassoulas <[email protected]>
1 parent ab775f6 commit 9098c60

File tree

5 files changed

+31
-6
lines changed

5 files changed

+31
-6
lines changed

CONTRIBUTORS.txt

+2
Original file line numberDiff line numberDiff line change
@@ -552,3 +552,5 @@ contributors:
552552
* Jaehoon Hwang (jaehoonhwang): contributor
553553

554554
* Samuel Forestier: contributor
555+
556+
* James DesLauriers: contributor

ChangeLog

+4
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ Release date: TBA
4040
* Added ``using-f-string-in-unsupported-version`` checker. Issued when ``py-version``
4141
is set to a version that does not support f-strings (< 3.6)
4242

43+
* Properly emit ``duplicate-key`` when Enum members are duplicate dictionary keys
44+
45+
Closes #5150
46+
4347
* Use ``py-version`` setting for alternative union syntax check (PEP 604),
4448
instead of the Python interpreter version.
4549

pylint/checkers/base.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -1452,9 +1452,13 @@ def visit_dict(self, node: nodes.Dict) -> None:
14521452
for k, _ in node.items:
14531453
if isinstance(k, nodes.Const):
14541454
key = k.value
1455-
if key in keys:
1456-
self.add_message("duplicate-key", node=node, args=key)
1457-
keys.add(key)
1455+
elif isinstance(k, nodes.Attribute):
1456+
key = k.as_string()
1457+
else:
1458+
continue
1459+
if key in keys:
1460+
self.add_message("duplicate-key", node=node, args=key)
1461+
keys.add(key)
14581462

14591463
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
14601464
"""update try...finally flag"""

tests/functional/d/duplicate_dict_literal_key.py

+14
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,25 @@
11
"""Check multiple key definition"""
22
# pylint: disable=pointless-statement, redundant-u-string-prefix
33

4+
from enum import Enum
5+
6+
7+
class MyEnum(Enum):
8+
""" Sample Enum for testing duplicate keys"""
9+
KEY = "key"
10+
11+
12+
413
correct_dict = {
514
'tea': 'for two',
615
'two': 'for tea',
716
}
817

18+
wrong_with_enum = { # [duplicate-key]
19+
MyEnum.KEY: "value 1",
20+
MyEnum.KEY: "value 2",
21+
}
22+
923
wrong_dict = { # [duplicate-key]
1024
'tea': 'for two',
1125
'two': 'for tea',
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1-
duplicate-key:9:13::Duplicate key 'tea' in dictionary
2-
duplicate-key:16:0::Duplicate key 1 in dictionary
3-
duplicate-key:17:0::Duplicate key 1.0 in dictionary
1+
duplicate-key:18:18::Duplicate key 'MyEnum.KEY' in dictionary:HIGH
2+
duplicate-key:23:13::Duplicate key 'tea' in dictionary:HIGH
3+
duplicate-key:30:0::Duplicate key 1 in dictionary:HIGH
4+
duplicate-key:31:0::Duplicate key 1.0 in dictionary:HIGH

0 commit comments

Comments
 (0)