Skip to content

Commit c372708

Browse files
authored
Merge pull request #43 from rtzoeller/attribute_assignment
Support keyword argument initialization of Structures
2 parents 081c93d + 933fd67 commit c372708

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

suitcase/structure.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,26 @@ class Structure(object):
242242
data=...'Hello, world!',
243243
)
244244
245+
Initialization via keyword argument is also supported::
246+
247+
>>> dgram = UDPDatagram(source_port=9110,
248+
... destination_port=1001,
249+
... checksum=27193,
250+
... data=b"Hello, world!")
251+
...
252+
>>> printb(dgram.pack())
253+
'#\x96\x03\xe9\x00\rj9Hello, world!'
254+
>>> dgram2 = UDPDatagram()
255+
>>> dgram2.unpack(dgram.pack())
256+
>>> dgram2
257+
UDPDatagram (
258+
source_port=9110,
259+
destination_port=1001,
260+
length=13,
261+
checksum=27193,
262+
data=...'Hello, world!',
263+
)
264+
245265
"""
246266

247267
@classmethod
@@ -263,7 +283,7 @@ def from_data(cls, data):
263283
m.unpack(data)
264284
return m
265285

266-
def __init__(self):
286+
def __init__(self, **kwargs):
267287
self._key_to_field = {}
268288
self._parent = None
269289
self._sorted_fields = []
@@ -278,6 +298,8 @@ def __init__(self):
278298
self._placeholder_to_field[field_placeholder] = field
279299
self._sorted_fields.append((key, field))
280300
self._packer = Packer(self._sorted_fields, self._crc_field)
301+
for key, value in kwargs.items():
302+
setattr(self, key, value)
281303

282304
def __getattr__(self, key):
283305
k2f = self.__dict__.get('_key_to_field', {})

suitcase/test/test_fields.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,5 +1198,21 @@ def test_dir(self):
11981198
self.assertTrue("value" in attrs)
11991199

12001200

1201+
class TestKeywordArgumentInitialization(unittest.TestCase):
1202+
def test_basic_assignment(self):
1203+
m = PascalString16(value=b"Hello World!")
1204+
self.assertEqual(m.pack(), b"\x00\x0cHello World!")
1205+
1206+
def test_nested_assignment(self):
1207+
m = NameStructure(first=PascalString16(value=b"John"),
1208+
last=PascalString16(value=b"Doe"))
1209+
self.assertEqual(m.pack(), b"\x00\x04John\x00\x03Doe")
1210+
1211+
def test_partial_assignment(self):
1212+
m = NameStructure(first=PascalString16(value=b"John"))
1213+
m.last = PascalString16(value=b"Doe")
1214+
self.assertEqual(m.pack(), b"\x00\x04John\x00\x03Doe")
1215+
1216+
12011217
if __name__ == "__main__":
12021218
unittest.main()

0 commit comments

Comments
 (0)