Skip to content

Commit e2e53e0

Browse files
committed
Inheritance instead of composition.
1 parent a6e7ca3 commit e2e53e0

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

canopen/objectdictionary/datatypes.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
DATA_TYPES = (VISIBLE_STRING, OCTET_STRING, UNICODE_STRING, DOMAIN)
3939

4040

41-
class UnsignedN:
41+
class UnsignedN(struct.Struct):
4242
"""Packing and unpacking unsigned integers of arbitrary width, like struct.Struct.
4343
4444
The width must be a multiple of 8 and must be between 8 and 64.
@@ -50,26 +50,27 @@ def __init__(self, width: int):
5050
if width <= 0 or width > 64:
5151
raise ValueError("Invalid width for UnsignedN")
5252
elif width <= 8:
53-
self.struct = struct.Struct("B")
53+
fmt = "B"
5454
elif width <= 16:
55-
self.struct = struct.Struct("<H")
55+
fmt = "<H"
5656
elif width <= 32:
57-
self.struct = struct.Struct("<L")
57+
fmt = "<L"
5858
else:
59-
self.struct = struct.Struct("<Q")
59+
fmt = "<Q"
60+
super().__init__(fmt)
6061

6162
def unpack(self, buffer):
62-
return self.struct.unpack(buffer + b'\x00' * (self.struct.size - self.size))
63+
return super().unpack(buffer + b'\x00' * (super().size - self.size))
6364

6465
def pack(self, *v):
65-
return self.struct.pack(*v)[:self.size]
66+
return super().pack(*v)[:self.size]
6667

6768
@property
68-
def size(self):
69+
def size(self) -> int:
6970
return self.width // 8
7071

7172

72-
class IntegerN:
73+
class IntegerN(struct.Struct):
7374
"""Packing and unpacking integers of arbitrary width, like struct.Struct.
7475
7576
The width must be a multiple of 8 and must be between 8 and 64.
@@ -81,22 +82,23 @@ def __init__(self, width: int):
8182
if width <= 0 or width > 64:
8283
raise ValueError("Invalid width for IntegerN")
8384
elif width <= 8:
84-
self.struct = struct.Struct("b")
85+
fmt = "b"
8586
elif width <= 16:
86-
self.struct = struct.Struct("<h")
87+
fmt = "<h"
8788
elif width <= 32:
88-
self.struct = struct.Struct("<l")
89+
fmt = "<l"
8990
else:
90-
self.struct = struct.Struct("<q")
91+
fmt = "<q"
92+
super().__init__(fmt)
9193

9294
def unpack(self, buffer):
9395
mask = 0x80
9496
neg = (buffer[self.size - 1] & mask) > 0
95-
return self.struct.unpack(buffer + (b'\xff' if neg else b'\x00') * (self.struct.size - self.size))
97+
return super().unpack(buffer + (b'\xff' if neg else b'\x00') * (super().size - self.size))
9698

9799
def pack(self, *v):
98-
return self.struct.pack(*v)[:self.size]
100+
return super().pack(*v)[:self.size]
99101

100102
@property
101-
def size(self):
103+
def size(self) -> int:
102104
return self.width // 8

0 commit comments

Comments
 (0)