Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup f-strings, logging and formats #443

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion canopen/emcy.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def get_desc(self) -> str:
return ""

def __str__(self):
text = "Code 0x{:04X}".format(self.code)
text = f"Code 0x{self.code:04X}"
description = self.get_desc()
if description:
text = text + ", " + description
Expand Down
2 changes: 1 addition & 1 deletion canopen/lss.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ def __send_configure(self, req_cs, value1=0, value2=0):
raise LssError("Response message is not for the request")

if error_code != ERROR_NONE:
error_msg = "LSS Error: %d" % error_code
error_msg = f"LSS Error: {error_code}"
raise LssError(error_msg)

def __send_command(self, message):
Expand Down
19 changes: 9 additions & 10 deletions canopen/objectdictionary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ def __getitem__(
if isinstance(index, str) and '.' in index:
idx, sub = index.split('.', maxsplit=1)
return self[idx][sub]
name = "0x%X" % index if isinstance(index, int) else index
raise KeyError("%s was not found in Object Dictionary" % name)
name = f"0x{index:X}" if isinstance(index, int) else index
sveinse marked this conversation as resolved.
Show resolved Hide resolved
raise KeyError(f"{name} was not found in Object Dictionary")
return item

def __setitem__(
Expand Down Expand Up @@ -185,7 +185,7 @@ def __repr__(self) -> str:
def __getitem__(self, subindex: Union[int, str]) -> "ODVariable":
item = self.names.get(subindex) or self.subindices.get(subindex)
if item is None:
raise KeyError("Subindex %s was not found" % subindex)
raise KeyError(f"Subindex {subindex} was not found")
sveinse marked this conversation as resolved.
Show resolved Hide resolved
return item

def __setitem__(self, subindex: Union[int, str], var: "ODVariable"):
Expand Down Expand Up @@ -249,7 +249,7 @@ def __getitem__(self, subindex: Union[int, str]) -> "ODVariable":
elif isinstance(subindex, int) and 0 < subindex < 256:
# Create a new variable based on first array item
template = self.subindices[1]
name = "%s_%x" % (template.name, subindex)
name = f"{template.name}_{subindex:x}"
acolomb marked this conversation as resolved.
Show resolved Hide resolved
var = ODVariable(name, self.index, subindex)
var.parent = self
for attr in ("data_type", "unit", "factor", "min", "max", "default",
Expand All @@ -258,7 +258,7 @@ def __getitem__(self, subindex: Union[int, str]) -> "ODVariable":
if attr in template.__dict__:
var.__dict__[attr] = template.__dict__[attr]
else:
raise KeyError("Could not find subindex %r" % subindex)
raise KeyError(f"Could not find subindex {subindex!r}")
acolomb marked this conversation as resolved.
Show resolved Hide resolved
return var

def __len__(self) -> int:
Expand Down Expand Up @@ -427,8 +427,7 @@ def encode_raw(self, value: Union[int, float, str, bytes, bytearray]) -> bytes:
raise ObjectDictionaryError("Data type has not been specified")
else:
raise TypeError(
"Do not know how to encode %r to data type %Xh" % (
value, self.data_type))
f"Do not know how to encode {value!r} to data type {self.data_type:X}h")
acolomb marked this conversation as resolved.
Show resolved Hide resolved

def decode_phys(self, value: int) -> Union[int, bool, float, str, bytes]:
if self.data_type in INTEGER_TYPES:
Expand All @@ -446,7 +445,7 @@ def decode_desc(self, value: int) -> str:
raise ObjectDictionaryError("No value descriptions exist")
elif value not in self.value_descriptions:
raise ObjectDictionaryError(
"No value description exists for %d" % value)
f"No value description exists for {value}")
else:
return self.value_descriptions[value]

Expand All @@ -458,8 +457,8 @@ def encode_desc(self, desc: str) -> int:
if description == desc:
return value
valid_values = ", ".join(self.value_descriptions.values())
error_text = "No value corresponds to '%s'. Valid values are: %s"
raise ValueError(error_text % (desc, valid_values))
raise ValueError(
f"No value corresponds to '{desc}'. Valid values are: {valid_values}")

def decode_bits(self, value: int, bits: List[int]) -> int:
try:
Expand Down
34 changes: 17 additions & 17 deletions canopen/objectdictionary/eds.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def import_eds(source, node_id):
if eds.has_section("Comments"):
linecount = int(eds.get("Comments", "Lines"), 0)
od.comments = '\n'.join([
eds.get("Comments", "Line%i" % line)
eds.get("Comments", f"Line{line}")
acolomb marked this conversation as resolved.
Show resolved Hide resolved
for line in range(1, linecount+1)
])

Expand All @@ -54,7 +54,7 @@ def import_eds(source, node_id):
else:
for rate in [10, 20, 50, 125, 250, 500, 800, 1000]:
baudPossible = int(
eds.get("DeviceInfo", "BaudRate_%i" % rate, fallback='0'), 0)
eds.get("DeviceInfo", f"BaudRate_{rate}", fallback='0'), 0)
if baudPossible != 0:
od.device_information.allowed_baudrates.add(rate*1000)

Expand Down Expand Up @@ -95,7 +95,7 @@ def import_eds(source, node_id):
match = re.match(r"^[Dd]ummy[Uu]sage$", section)
if match is not None:
for i in range(1, 8):
key = "Dummy%04d" % i
key = f"Dummy{i:04d}"
if eds.getint(section, key) == 1:
var = objectdictionary.ODVariable(key, i, 0)
var.data_type = i
Expand Down Expand Up @@ -241,7 +241,7 @@ def _revert_variable(var_type, value):
elif var_type in datatypes.FLOAT_TYPES:
return value
else:
return "0x%02X" % value
return f"0x{value:02X}"


def build_variable(eds, section, node_id, index, subindex=0):
Expand All @@ -266,7 +266,7 @@ def build_variable(eds, section, node_id, index, subindex=0):
# The eds.get function gives us 0x00A0 now convert to String without hex representation and upper case
# The sub2 part is then the section where the type parameter stands
try:
var.data_type = int(eds.get("%Xsub1" % var.data_type, "DefaultValue"), 0)
var.data_type = int(eds.get(f"{var.data_type:X}sub1", "DefaultValue"), 0)
except NoSectionError:
logger.warning("%s has an unknown or unsupported data type (%X)", name, var.data_type)
# Assume DOMAIN to force application to interpret the byte data
Expand Down Expand Up @@ -356,15 +356,15 @@ def export_common(var, eds, section):
def export_variable(var, eds):
if isinstance(var.parent, ObjectDictionary):
# top level variable
section = "%04X" % var.index
section = f"{var.index:04X}"
else:
# nested variable
section = "%04Xsub%X" % (var.index, var.subindex)
section = f"{var.index:04X}sub{var.subindex:X}"

export_common(var, eds, section)
eds.set(section, "ObjectType", "0x%X" % VAR)
eds.set(section, "ObjectType", f"0x{VAR:X}")
acolomb marked this conversation as resolved.
Show resolved Hide resolved
if var.data_type:
eds.set(section, "DataType", "0x%04X" % var.data_type)
eds.set(section, "DataType", f"0x{var.data_type:04X}")
if var.access_type:
eds.set(section, "AccessType", var.access_type)

Expand All @@ -381,7 +381,7 @@ def export_variable(var, eds):
eds.set(section, "ParameterValue",
_revert_variable(var.data_type, var.value))

eds.set(section, "DataType", "0x%04X" % var.data_type)
eds.set(section, "DataType", f"0x{var.data_type:04X}")
eds.set(section, "PDOMapping", hex(var.pdo_mappable))

if getattr(var, 'min', None) is not None:
Expand All @@ -397,11 +397,11 @@ def export_variable(var, eds):
eds.set(section, "Unit", var.unit)

def export_record(var, eds):
section = "%04X" % var.index
section = f"{var.index:04X}"
export_common(var, eds, section)
eds.set(section, "SubNumber", "0x%X" % len(var.subindices))
eds.set(section, "SubNumber", f"0x{len(var.subindices):X}")
ot = RECORD if isinstance(var, objectdictionary.ODRecord) else ARR
eds.set(section, "ObjectType", "0x%X" % ot)
eds.set(section, "ObjectType", f"0x{ot:X}")
for i in var:
export_variable(var[i], eds)

Expand Down Expand Up @@ -463,7 +463,7 @@ def export_record(var, eds):
for rate in od.device_information.allowed_baudrates.union(
{10e3, 20e3, 50e3, 125e3, 250e3, 500e3, 800e3, 1000e3}):
eds.set(
"DeviceInfo", "BaudRate_%i" % (rate/1000),
"DeviceInfo", f"BaudRate_{rate//1000}",
acolomb marked this conversation as resolved.
Show resolved Hide resolved
int(rate in od.device_information.allowed_baudrates))

if device_commisioning and (od.bitrate or od.node_id):
Expand All @@ -477,12 +477,12 @@ def export_record(var, eds):
i = 0
for line in od.comments.splitlines():
i += 1
eds.set("Comments", "Line%i" % i, line)
eds.set("Comments", f"Line{i}", line)
eds.set("Comments", "Lines", i)

eds.add_section("DummyUsage")
for i in range(1, 8):
key = "Dummy%04d" % i
key = f"Dummy{i:04d}"
eds.set("DummyUsage", key, 1 if (key in od) else 0)

def mandatory_indices(x):
Expand All @@ -506,7 +506,7 @@ def add_list(section, list):
eds.add_section(section)
eds.set(section, "SupportedObjects", len(list))
for i in range(0, len(list)):
eds.set(section, (i + 1), "0x%04X" % list[i])
eds.set(section, (i + 1), f"0x{list[i]:04X}")
for index in list:
export_object(od[index], eds)

Expand Down
12 changes: 6 additions & 6 deletions canopen/pdo/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __getitem__(self, key):
except KeyError:
# ignore if one specific PDO does not have the key and try the next one
continue
raise KeyError("PDO: {0} was not found in any map".format(key))
raise KeyError(f"PDO: {key} was not found in any map")

def __len__(self):
return len(self.map)
Expand Down Expand Up @@ -201,8 +201,8 @@ def __getitem_by_index(self, value):
valid_values.append(var.index)
if var.index == value:
return var
raise KeyError('{0} not found in map. Valid entries are {1}'.format(
value, ', '.join(str(v) for v in valid_values)))
raise KeyError(f'{value} not found in map. Valid entries are ' +
", ".join(str(v) for v in valid_values))
acolomb marked this conversation as resolved.
Show resolved Hide resolved

def __getitem_by_name(self, value):
valid_values = []
Expand All @@ -211,8 +211,8 @@ def __getitem_by_name(self, value):
valid_values.append(var.name)
if var.name == value:
return var
raise KeyError('{0} not found in map. Valid entries are {1}'.format(
value, ', '.join(valid_values)))
raise KeyError(f'{value} not found in map. Valid entries are ' +
', '.join(valid_values))
acolomb marked this conversation as resolved.
Show resolved Hide resolved

def __getitem__(self, key: Union[int, str]) -> "PdoVariable":
var = None
Expand Down Expand Up @@ -272,7 +272,7 @@ def name(self) -> str:
if direction == "Rx":
map_id -= 1
node_id = self.cob_id & 0x7F
return "%sPDO%d_node%d" % (direction, map_id, node_id)
return f"{direction}PDO{map_id}_node{node_id}"

@property
def is_periodic(self) -> bool:
Expand Down
14 changes: 6 additions & 8 deletions canopen/profiles/p402.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def homing(self, timeout=None, restore_op_mode=False):
homingstatus = self._homing_status()
if homingstatus in ('INTERRUPTED', 'ERROR VELOCITY IS NOT ZERO',
'ERROR VELOCITY IS ZERO'):
raise RuntimeError('Unable to home. Reason: {0}'.format(homingstatus))
raise RuntimeError(f'Unable to home. Reason: {homingstatus}')
if timeout and time.monotonic() > t:
raise RuntimeError('Unable to home, timeout reached')
logger.info('Homing mode carried out successfully.')
Expand Down Expand Up @@ -397,8 +397,7 @@ def op_mode(self):
if pdo.is_periodic:
timestamp = pdo.wait_for_reception(timeout=self.TIMEOUT_CHECK_TPDO)
if timestamp is None:
raise RuntimeError("Timeout getting node {0}'s mode of operation.".format(
self.id))
raise RuntimeError(f"Timeout getting node {self.id}'s mode of operation.")
code = self.tpdo_values[0x6061]
except KeyError:
logger.warning('The object 0x6061 is not a configured TPDO, fallback to SDO')
Expand All @@ -410,7 +409,7 @@ def op_mode(self, mode):
try:
if not self.is_op_mode_supported(mode):
raise TypeError(
'Operation mode {m} not suppported on node {n}.'.format(n=self.id, m=mode))
f'Operation mode {mode} not suppported on node {self.id}.')
# Update operation mode in RPDO if possible, fall back to SDO
if 0x6060 in self.rpdo_pointers:
self.rpdo_pointers[0x6060].raw = OperationMode.NAME2CODE[mode]
Expand All @@ -423,8 +422,7 @@ def op_mode(self, mode):
while self.op_mode != mode:
if time.monotonic() > timeout:
raise RuntimeError(
"Timeout setting node {0}'s new mode of operation to {1}.".format(
self.id, mode))
f"Timeout setting node {self.id}'s new mode of operation to {mode}.")
logger.info('Set node {n} operation mode to {m}.'.format(n=self.id, m=mode))
except SdoCommunicationError as e:
logger.warning('[SDO communication error] Cause: {0}'.format(str(e)))
Expand Down Expand Up @@ -561,7 +559,7 @@ def _next_state(self, target_state):
'FAULT REACTION ACTIVE',
'FAULT'):
raise ValueError(
'Target state {} cannot be entered programmatically'.format(target_state))
f'Target state {target_state} cannot be entered programmatically')
from_state = self.state
if (from_state, target_state) in State402.TRANSITIONTABLE:
return target_state
Expand All @@ -573,7 +571,7 @@ def _change_state(self, target_state):
self.controlword = State402.TRANSITIONTABLE[(self.state, target_state)]
except KeyError:
raise ValueError(
'Illegal state transition from {f} to {t}'.format(f=self.state, t=target_state))
f'Illegal state transition from {self.state} to {target_state}')
timeout = time.monotonic() + self.TIMEOUT_SWITCH_STATE_SINGLE
while self.state != target_state:
if time.monotonic() > timeout:
Expand Down
8 changes: 4 additions & 4 deletions canopen/profiles/tools/test_p402_states.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,19 @@
if target_state == from_state:
continue
if (from_state, target_state) in State402.TRANSITIONTABLE:
print('direct:\t{} -> {}'.format(from_state, target_state))
print(f'direct:\t{from_state} -> {target_state}')
else:
next_state = State402.next_state_indirect(from_state)
if not next_state:
print('FAIL:\t{} -> {}'.format(from_state, next_state))
print(f'FAIL:\t{from_state} -> {next_state}')
else:
print('\t{} -> {} ...'.format(from_state, next_state))
print(f'\t{from_state} -> {next_state} ...')

try:
while from_state != target_state:
n.tpdo_values[0x6041] = State402.SW_MASK[from_state][1]
next_state = n._next_state(target_state)
print('\t\t-> {}'.format(next_state))
print(f'\t\t-> {next_state}')
from_state = next_state
except ValueError:
print('\t\t-> disallowed!')
Loading
Loading