Skip to content

Commit a4f927b

Browse files
committed
Raise TypeError when requesting value description of non-int data.
According to the type hints, the mapping mechanism was only ever intended for integers (emulating an enumeration). Avoids a later DictionaryError for the missing key and some type checker errors because decode_desc() shall only accept int. Add the same check in the write()-based variable access API.
1 parent 2f914ff commit a4f927b

1 file changed

Lines changed: 11 additions & 2 deletions

File tree

canopen/variable.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,14 @@ def phys(self, value: Union[int, bool, float, str, bytes]):
111111

112112
@property
113113
def desc(self) -> str:
114-
"""Converts to and from a description of the value as a string."""
115-
value = self.od.decode_desc(self.raw)
114+
"""Convert to and from a description of the value as a string.
115+
116+
:raises TypeError: If the received raw data was anything but an integer value.
117+
"""
118+
raw_int = self.raw
119+
if not isinstance(raw_int, int):
120+
raise TypeError("Description of values only supported for integer objects")
121+
value = self.od.decode_desc(raw_int)
116122
logger.debug("Description is '%s'", value)
117123
return value
118124

@@ -160,12 +166,15 @@ def write(
160166
- 'raw'
161167
- 'phys'
162168
- 'desc'
169+
:raises TypeError: If the "desc" format was specified with anything but a string value.
163170
"""
164171
if fmt == "raw":
165172
self.raw = value
166173
elif fmt == "phys":
167174
self.phys = value
168175
elif fmt == "desc":
176+
if not isinstance(value, str):
177+
raise TypeError("fmt=desc requires a string value")
169178
self.desc = value
170179

171180

0 commit comments

Comments
 (0)