Skip to content

Commit f2fb7f4

Browse files
committed
lib.data: raise ValueError if initializer refers to nonexistent key.
Previously, `KeyError` was raised, which should not be escaping the implementation (`Layout.const` is not a retrieval method).
1 parent 94becb5 commit f2fb7f4

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

amaranth/lib/data.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -219,12 +219,16 @@ def const(self, init):
219219
elif isinstance(init, Sequence):
220220
iterator = enumerate(init)
221221
else:
222-
raise TypeError("Layout constant initializer must be a mapping or a sequence, not {!r}"
223-
.format(init))
222+
raise TypeError(f"Layout constant initializer must be a mapping or a sequence, not "
223+
f"{init!r}")
224224

225225
int_value = 0
226226
for key, key_value in iterator:
227-
field = self[key]
227+
try:
228+
field = self[key]
229+
except KeyError:
230+
raise ValueError(f"Layout constant initializer refers to key {key!r}, which is not "
231+
f"a part of the layout")
228232
cast_field_shape = Shape.cast(field.shape)
229233
if isinstance(field.shape, ShapeCastable):
230234
key_value = hdl.Const.cast(hdl.Const(key_value, field.shape))

tests/test_lib_data.py

+4
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,10 @@ def test_const_wrong(self):
477477
r"^Layout constant initializer must be a mapping or a sequence, not "
478478
r"<.+?object.+?>$"):
479479
sl.const(object())
480+
with self.assertRaisesRegex(ValueError,
481+
r"^Layout constant initializer refers to key 'g', which is not a part "
482+
r"of the layout$"):
483+
sl.const({"g": 1})
480484
sl2 = data.StructLayout({"f": unsigned(2)})
481485
with self.assertRaisesRegex(ValueError,
482486
r"^Const layout StructLayout.* differs from shape layout StructLayout.*$"):

0 commit comments

Comments
 (0)