Skip to content

Commit fcc4f54

Browse files
committed
lib.data: make Field() immutable.
Mutability of Field isn't specified by the RFC and can cause issues if the objects stored in Layout subclasses are mutated. There isn't any reason to do that (the subclasses themselves are mutable and handle that correctly), so disallow it.
1 parent e2f0519 commit fcc4f54

File tree

2 files changed

+15
-17
lines changed

2 files changed

+15
-17
lines changed

amaranth/lib/data.py

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,33 +13,25 @@
1313

1414
class Field:
1515
def __init__(self, shape, offset):
16-
self.shape = shape
17-
self.offset = offset
18-
19-
@property
20-
def shape(self):
21-
return self._shape
22-
23-
@shape.setter
24-
def shape(self, shape):
2516
try:
2617
Shape.cast(shape)
2718
except TypeError as e:
2819
raise TypeError("Field shape must be a shape-castable object, not {!r}"
2920
.format(shape)) from e
30-
self._shape = shape
31-
32-
@property
33-
def offset(self):
34-
return self._offset
35-
36-
@offset.setter
37-
def offset(self, offset):
3821
if not isinstance(offset, int) or offset < 0:
3922
raise TypeError("Field offset must be a non-negative integer, not {!r}"
4023
.format(offset))
24+
self._shape = shape
4125
self._offset = offset
4226

27+
@property
28+
def shape(self):
29+
return self._shape
30+
31+
@property
32+
def offset(self):
33+
return self._offset
34+
4335
@property
4436
def width(self):
4537
return Shape.cast(self.shape).width

tests/test_lib_data.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ def test_offset_wrong(self):
5959
r"^Field offset must be a non-negative integer, not -1$"):
6060
Field(unsigned(2), -1)
6161

62+
def test_immutable(self):
63+
with self.assertRaises(AttributeError):
64+
Field(1, 0).shape = unsigned(2)
65+
with self.assertRaises(AttributeError):
66+
Field(1, 0).offset = 1
67+
6268

6369
class StructLayoutTestCase(TestCase):
6470
def test_construct(self):

0 commit comments

Comments
 (0)