Skip to content

Commit 5587d9a

Browse files
committed
Correct type annotations for class Bits.
This mechanism works only for integers, so add appropriate assertions. Document all expected types for indexing the Bits.
1 parent dcf7bf4 commit 5587d9a

1 file changed

Lines changed: 16 additions & 13 deletions

File tree

canopen/variable.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
from __future__ import annotations
2+
13
import logging
2-
from collections.abc import Mapping
4+
from collections.abc import Collection, Mapping
35
from typing import Union
46

57
from canopen import objectdictionary
@@ -118,7 +120,7 @@ def desc(self, desc: str):
118120
self.raw = self.od.encode_desc(desc)
119121

120122
@property
121-
def bits(self) -> "Bits":
123+
def bits(self) -> Bits:
122124
"""Access bits using integers, slices, or bit descriptions."""
123125
return Bits(self)
124126

@@ -169,23 +171,23 @@ def write(
169171
class Bits(Mapping):
170172

171173
def __init__(self, variable: Variable):
174+
assert variable.od.data_type in objectdictionary.datatypes.INTEGER_TYPES
172175
self.variable = variable
173176
self.read()
177+
self.raw: int
174178

175179
@staticmethod
176-
def _get_bits(key):
180+
def _get_bits(key: Union[slice, int, str, Collection[int]]) -> Union[str, Collection[int]]:
177181
if isinstance(key, slice):
178-
bits = range(key.start, key.stop, key.step)
179-
elif isinstance(key, int):
180-
bits = [key]
181-
else:
182-
bits = key
183-
return bits
184-
185-
def __getitem__(self, key) -> int:
182+
return range(key.start, key.stop, key.step)
183+
if isinstance(key, int):
184+
return [key]
185+
return key
186+
187+
def __getitem__(self, key: Union[slice, int, str, Collection[int]]) -> int:
186188
return self.variable.od.decode_bits(self.raw, self._get_bits(key))
187189

188-
def __setitem__(self, key, value: int):
190+
def __setitem__(self, key: Union[slice, int, str, Collection[int]], value: int):
189191
self.raw = self.variable.od.encode_bits(
190192
self.raw, self._get_bits(key), value)
191193
self.write()
@@ -197,7 +199,8 @@ def __len__(self):
197199
return len(self.variable.od.bit_definitions)
198200

199201
def read(self):
200-
self.raw = self.variable.raw
202+
assert isinstance(raw_int := self.variable.raw, int)
203+
self.raw = raw_int
201204

202205
def write(self):
203206
self.variable.raw = self.raw

0 commit comments

Comments
 (0)