Skip to content

Commit 7bf3928

Browse files
karldingfelixdivo
authored andcommitted
Add typing annotations for can.util
This adds typing annotations for functions in can.util. In addition, this remove the redundant typing information that was previously in the docstring, since we now have sphinx-autodoc-typehints to generate the types for the docs from the annotations in the function signature. This works towards PEP 561 compatibility.
1 parent 68855df commit 7bf3928

File tree

2 files changed

+25
-18
lines changed

2 files changed

+25
-18
lines changed

can/typechecking.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,5 @@
2727
FileLike = typing.IO[typing.Any]
2828
StringPathLike = typing.Union[str, "os.PathLike[str]"]
2929
AcceptedIOType = typing.Optional[typing.Union[FileLike, StringPathLike]]
30+
31+
BusConfig = typing.NewType("BusConfig", dict)

can/util.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
Utilities and configuration file parsing.
33
"""
44

5+
from typing import Dict, Optional, Union
6+
7+
from can import typechecking
8+
59
import json
610
import os
711
import os.path
@@ -29,7 +33,9 @@
2933
CONFIG_FILES.extend(["can.ini", os.path.join(os.getenv("APPDATA", ""), "can.ini")])
3034

3135

32-
def load_file_config(path=None, section="default"):
36+
def load_file_config(
37+
path: Optional[typechecking.AcceptedIOType] = None, section: str = "default"
38+
) -> Dict[str, str]:
3339
"""
3440
Loads configuration from file with following content::
3541
@@ -57,7 +63,7 @@ def load_file_config(path=None, section="default"):
5763
return _config
5864

5965

60-
def load_environment_config(context=None):
66+
def load_environment_config(context: Optional[str] = None) -> Dict[str, str]:
6167
"""
6268
Loads config dict from environmental variables (if set):
6369
@@ -83,20 +89,22 @@ def load_environment_config(context=None):
8389

8490
context_suffix = "_{}".format(context) if context else ""
8591

86-
config = {}
87-
8892
can_config_key = "CAN_CONFIG" + context_suffix
89-
if can_config_key in os.environ:
90-
config = json.loads(os.environ.get(can_config_key))
93+
config: Dict[str, str] = json.loads(os.environ.get(can_config_key, "{}"))
9194

9295
for key, val in mapper.items():
93-
if val in os.environ:
94-
config[key] = os.environ.get(val + context_suffix)
96+
config_option = os.environ.get(val + context_suffix, None)
97+
if config_option:
98+
config[key] = config_option
9599

96100
return config
97101

98102

99-
def load_config(path=None, config=None, context=None):
103+
def load_config(
104+
path: Optional[typechecking.AcceptedIOType] = None,
105+
config=None,
106+
context: Optional[str] = None,
107+
) -> typechecking.BusConfig:
100108
"""
101109
Returns a dict with configuration details which is loaded from (in this order):
102110
@@ -213,26 +221,25 @@ def load_config(path=None, config=None, context=None):
213221
return config
214222

215223

216-
def set_logging_level(level_name=None):
224+
def set_logging_level(level_name: Optional[str] = None):
217225
"""Set the logging level for the "can" logger.
218226
Expects one of: 'critical', 'error', 'warning', 'info', 'debug', 'subdebug'
219227
"""
220228
can_logger = logging.getLogger("can")
221229

222230
try:
223-
can_logger.setLevel(getattr(logging, level_name.upper()))
231+
can_logger.setLevel(getattr(logging, level_name.upper())) # type: ignore
224232
except AttributeError:
225233
can_logger.setLevel(logging.DEBUG)
226234
log.debug("Logging set to {}".format(level_name))
227235

228236

229-
def len2dlc(length):
237+
def len2dlc(length: int) -> int:
230238
"""Calculate the DLC from data length.
231239
232240
:param int length: Length in number of bytes (0-64)
233241
234242
:returns: DLC (0-15)
235-
:rtype: int
236243
"""
237244
if length <= 8:
238245
return length
@@ -242,25 +249,23 @@ def len2dlc(length):
242249
return 15
243250

244251

245-
def dlc2len(dlc):
252+
def dlc2len(dlc: int) -> int:
246253
"""Calculate the data length from DLC.
247254
248-
:param int dlc: DLC (0-15)
255+
:param dlc: DLC (0-15)
249256
250257
:returns: Data length in number of bytes (0-64)
251-
:rtype: int
252258
"""
253259
return CAN_FD_DLC[dlc] if dlc <= 15 else 64
254260

255261

256-
def channel2int(channel):
262+
def channel2int(channel: Optional[Union[typechecking.Channel]]) -> Optional[int]:
257263
"""Try to convert the channel to an integer.
258264
259265
:param channel:
260266
Channel string (e.g. can0, CAN1) or integer
261267
262268
:returns: Channel integer or `None` if unsuccessful
263-
:rtype: int
264269
"""
265270
if channel is None:
266271
return None

0 commit comments

Comments
 (0)