Skip to content

Commit 0bf0141

Browse files
util/yaml: warn on duplicate keys in mappings
When adding drivers/resources to an environment config or resources to an exporter config, users can stumble upon redundant keys. The resulting errors are not obvious, the last key simply overrides any previous entries with the same key. In order to make these config errors more obvious, emit a warning when duplicate keys are detected in mappings. Signed-off-by: Bastian Krause <[email protected]>
1 parent 8599a03 commit 0bf0141

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

labgrid/util/yaml.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
This module contains the custom YAML load and dump functions and associated
33
loader and dumper
44
"""
5+
6+
import warnings
57
from collections import OrderedDict, UserString
68
from string import Template
79

@@ -16,7 +18,19 @@ class Dumper(yaml.SafeDumper):
1618
pass
1719

1820

21+
def _check_duplicate_dict_keys(loader, node):
22+
seen_keys = []
23+
for key_node, _ in node.value:
24+
key = loader.construct_scalar(key_node)
25+
if key in seen_keys:
26+
warnings.warn(
27+
f"{loader.name}: previous entry with duplicate YAML dictionary key '{key}' overwritten", UserWarning
28+
)
29+
seen_keys.append(key)
30+
31+
1932
def _dict_constructor(loader, node):
33+
_check_duplicate_dict_keys(loader, node)
2034
return OrderedDict(loader.construct_pairs(node))
2135

2236

0 commit comments

Comments
 (0)