Skip to content

Commit e03464b

Browse files
committed
Add typing annotations for functions in can.bus
This adds typing annotations for use via mypy for all functions under can.bus. This works towards PEP 561 compatibility.
1 parent acda992 commit e03464b

File tree

1 file changed

+40
-18
lines changed

1 file changed

+40
-18
lines changed

can/bus.py

Lines changed: 40 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
Contains the ABC bus implementation and its documentation.
55
"""
66

7+
from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Union
8+
79
from abc import ABCMeta, abstractmethod
810
import can
911
import logging
@@ -38,7 +40,12 @@ class BusABC(metaclass=ABCMeta):
3840
RECV_LOGGING_LEVEL = 9
3941

4042
@abstractmethod
41-
def __init__(self, channel, can_filters=None, **kwargs):
43+
def __init__(
44+
self,
45+
channel: Any,
46+
can_filters: Optional[List[Dict[str, Union[bool, int, str]]]] = None,
47+
**kwargs: object
48+
):
4249
"""Construct and open a CAN bus instance of the specified type.
4350
4451
Subclasses should call though this method with all given parameters
@@ -53,13 +60,13 @@ def __init__(self, channel, can_filters=None, **kwargs):
5360
:param dict kwargs:
5461
Any backend dependent configurations are passed in this dictionary
5562
"""
56-
self._periodic_tasks = []
63+
self._periodic_tasks: List[can.broadcastmanager.CyclicSendTaskABC] = []
5764
self.set_filters(can_filters)
5865

59-
def __str__(self):
66+
def __str__(self) -> str:
6067
return self.channel_info
6168

62-
def recv(self, timeout=None):
69+
def recv(self, timeout: Optional[float] = None) -> Optional[can.Message]:
6370
"""Block waiting for a message from the Bus.
6471
6572
:type timeout: float or None
@@ -100,7 +107,7 @@ def recv(self, timeout=None):
100107
else:
101108
return None
102109

103-
def _recv_internal(self, timeout):
110+
def _recv_internal(self, timeout: Optional[float]):
104111
"""
105112
Read a message from the bus and tell whether it was filtered.
106113
This methods may be called by :meth:`~can.BusABC.recv`
@@ -144,7 +151,7 @@ def _recv_internal(self, timeout):
144151
raise NotImplementedError("Trying to read from a write only bus?")
145152

146153
@abstractmethod
147-
def send(self, msg, timeout=None):
154+
def send(self, msg: can.Message, timeout: Optional[float] = None):
148155
"""Transmit a message to the CAN bus.
149156
150157
Override this method to enable the transmit path.
@@ -164,7 +171,13 @@ def send(self, msg, timeout=None):
164171
"""
165172
raise NotImplementedError("Trying to write to a readonly bus?")
166173

167-
def send_periodic(self, msgs, period, duration=None, store_task=True):
174+
def send_periodic(
175+
self,
176+
msgs: Union[Sequence[can.Message], can.Message],
177+
period: float,
178+
duration: Optional[float] = None,
179+
store_task: bool = True,
180+
) -> can.broadcastmanager.CyclicSendTaskABC:
168181
"""Start sending messages at a given period on this bus.
169182
170183
The task will be active until one of the following conditions are met:
@@ -223,14 +236,19 @@ def wrapped_stop_method(remove_task=True):
223236
pass
224237
original_stop_method()
225238

226-
task.stop = wrapped_stop_method
239+
setattr(task, "stop", wrapped_stop_method)
227240

228241
if store_task:
229242
self._periodic_tasks.append(task)
230243

231244
return task
232245

233-
def _send_periodic_internal(self, msgs, period, duration=None):
246+
def _send_periodic_internal(
247+
self,
248+
msgs: Union[Sequence[can.Message], can.Message],
249+
period: float,
250+
duration: Optional[float] = None,
251+
) -> can.broadcastmanager.CyclicSendTaskABC:
234252
"""Default implementation of periodic message sending using threading.
235253
236254
Override this method to enable a more efficient backend specific approach.
@@ -275,7 +293,7 @@ def stop_all_periodic_tasks(self, remove_tasks=True):
275293
if remove_tasks:
276294
self._periodic_tasks = []
277295

278-
def __iter__(self):
296+
def __iter__(self) -> Iterator[can.Message]:
279297
"""Allow iteration on messages as they are received.
280298
281299
>>> for msg in bus:
@@ -291,18 +309,20 @@ def __iter__(self):
291309
yield msg
292310

293311
@property
294-
def filters(self):
312+
def filters(self) -> Optional[Iterable[dict]]:
295313
"""
296314
Modify the filters of this bus. See :meth:`~can.BusABC.set_filters`
297315
for details.
298316
"""
299317
return self._filters
300318

301319
@filters.setter
302-
def filters(self, filters):
320+
def filters(self, filters: Optional[Iterable[Dict[str, Union[bool, int, str]]]]):
303321
self.set_filters(filters)
304322

305-
def set_filters(self, filters=None):
323+
def set_filters(
324+
self, filters: Optional[Iterable[Dict[str, Union[bool, int, str]]]] = None
325+
):
306326
"""Apply filtering to all messages received by this Bus.
307327
308328
All messages that match at least one filter are returned.
@@ -327,7 +347,9 @@ def set_filters(self, filters=None):
327347
self._filters = filters or None
328348
self._apply_filters(self._filters)
329349

330-
def _apply_filters(self, filters):
350+
def _apply_filters(
351+
self, filters: Optional[Iterable[Dict[str, Union[bool, int, str]]]]
352+
):
331353
"""
332354
Hook for applying the filters to the underlying kernel or
333355
hardware if supported/implemented by the interface.
@@ -336,7 +358,7 @@ def _apply_filters(self, filters):
336358
See :meth:`~can.BusABC.set_filters` for details.
337359
"""
338360

339-
def _matches_filters(self, msg):
361+
def _matches_filters(self, msg: can.Message) -> bool:
340362
"""Checks whether the given message matches at least one of the
341363
current filters. See :meth:`~can.BusABC.set_filters` for details
342364
on how the filters work.
@@ -388,7 +410,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):
388410
self.shutdown()
389411

390412
@property
391-
def state(self):
413+
def state(self) -> BusState:
392414
"""
393415
Return the current state of the hardware
394416
@@ -397,7 +419,7 @@ def state(self):
397419
return BusState.ACTIVE
398420

399421
@state.setter
400-
def state(self, new_state):
422+
def state(self, new_state: BusState):
401423
"""
402424
Set the new state of the hardware
403425
@@ -406,7 +428,7 @@ def state(self, new_state):
406428
raise NotImplementedError("Property is not implemented.")
407429

408430
@staticmethod
409-
def _detect_available_configs():
431+
def _detect_available_configs() -> Iterator[dict]:
410432
"""Detect all configurations/channels that this interface could
411433
currently connect with.
412434

0 commit comments

Comments
 (0)