hdl.rec: use a helpful error on unknown field reference.
authorwhitequark <whitequark@whitequark.org>
Tue, 1 Jan 2019 03:35:34 +0000 (03:35 +0000)
committerwhitequark <whitequark@whitequark.org>
Tue, 1 Jan 2019 03:35:34 +0000 (03:35 +0000)
nmigen/hdl/rec.py
nmigen/test/test_hdl_rec.py

index 32028afcdd7aafe0bfb989a7d31ff3180d22625e..f291087a7ef5279819903e5bedfd8a3b9facedd0 100644 (file)
@@ -87,10 +87,14 @@ class Record(Value):
                 self.fields[field_name] = Signal(field_shape, name=concat(name, field_name))
 
     def __getattr__(self, name):
-        return self.fields[name]
+        return self[name]
 
     def __getitem__(self, name):
-        return self.fields[name]
+        try:
+            return self.fields[name]
+        except KeyError:
+            raise NameError("Record does not have a field '{}'. Did you mean one of: {}?"
+                            .format(name, ", ".join(self.fields))) from None
 
     def shape(self):
         return sum(len(f) for f in self.fields.values()), False
index 501fda912177289ba9c039a3188a017b5d2bd272..dd5cb7be8aa980b993c97376303babaa17858a93 100644 (file)
@@ -78,3 +78,12 @@ class RecordTestCase(FHDLTestCase):
 
         self.assertEqual(repr(r), "(rec <unnamed> stb)")
         self.assertEqual(r.stb.name, "stb")
+
+    def test_wrong_field(self):
+        r = Record([
+            ("stb", 1),
+            ("ack", 1),
+        ])
+        with self.assertRaises(NameError,
+                msg="Record does not have a field 'en'. Did you mean one of: stb, ack?"):
+            r.en