refactor: Use f-strings for more exceptions and log message

Semi manually convert remaining strings with no translation to f-string.
This commit is contained in:
Matthias Hagmann 2024-03-24 11:29:38 +01:00 committed by Peter F. Patel-Schneider
parent d1d3d71091
commit 4e6361429e
12 changed files with 28 additions and 28 deletions

View File

@ -397,7 +397,7 @@ def write(device_handle, data):
else:
break
if bytes_written != len(data):
raise OSError(_errno.EIO, "written %d bytes out of expected %d" % (bytes_written, len(data)))
raise OSError(_errno.EIO, f"written {int(bytes_written)} bytes out of expected {len(data)}")
def read(device_handle, bytes_count, timeout_ms=-1):
@ -422,7 +422,7 @@ def read(device_handle, bytes_count, timeout_ms=-1):
if xlist:
assert xlist == [device_handle]
raise OSError(_errno.EIO, "exception on file descriptor %d" % device_handle)
raise OSError(_errno.EIO, f"exception on file descriptor {int(device_handle)}")
if rlist:
assert rlist == [device_handle]

View File

@ -345,7 +345,7 @@ class NamedInt(int):
return self.name
def __repr__(self):
return "NamedInt(%d, %r)" % (int(self), self.name)
return f"NamedInt({int(self)}, {self.name!r})"
@classmethod
def from_yaml(cls, loader, node):
@ -475,9 +475,9 @@ class NamedInts:
raise TypeError("name must be a string")
if str(value) in self.__dict__:
raise ValueError("%s (%d) already known" % (value, int(value)))
raise ValueError(f"{value} ({int(int(value))}) already known")
if int(value) in self._indexed:
raise ValueError("%d (%s) already known" % (int(value), value))
raise ValueError(f"{int(int(value))} ({value}) already known")
self._values.append(value)
self._is_sorted = False

View File

@ -542,7 +542,7 @@ class Device:
name = self._name or self._codename or "?"
except exceptions.NoSuchDevice:
name = "name not available"
return "<Device(%d,%s,%s,%s)>" % (self.number, self.wpid or self.product_id, name, self.serial)
return f"<Device({int(self.number)},{self.wpid or self.product_id},{name},{self.serial})>"
__repr__ = __str__

View File

@ -1266,11 +1266,11 @@ class MouseClick(Action):
self.count = 1
def __str__(self):
return "MouseClick: %s (%d)" % (self.button, self.count)
return f"MouseClick: {self.button} ({int(self.count)})"
def evaluate(self, feature, notification, device, last_result):
if logger.isEnabledFor(logging.INFO):
logger.info("MouseClick action: %d %s" % (self.count, self.button))
logger.info(f"MouseClick action: {int(self.count)} {self.button}")
if self.button and self.count:
click(buttons[self.button], self.count)
_time.sleep(0.01)

View File

@ -203,7 +203,7 @@ class Receiver:
def register_new_device(self, number, notification=None):
if self._devices.get(number) is not None:
raise IndexError("%s: device number %d already registered" % (self, number))
raise IndexError(f"{self}: device number {int(number)} already registered")
assert notification is None or notification.devnumber == number
assert notification is None or notification.sub_id == 0x41

View File

@ -773,7 +773,7 @@ class DpiSlidingXY(_RawXYProcessing):
def displayNewDpi(self, newDpiIdx):
if _notify.available:
reason = "DPI %d [min %d, max %d]" % (self.dpiChoices[newDpiIdx], self.dpiChoices[0], self.dpiChoices[-1])
reason = f"DPI {int(self.dpiChoices[newDpiIdx])} [min {int(self.dpiChoices[0])}, max {int(self.dpiChoices[-1])}]"
_notify.show(self.device, reason)
def press_action(self, key): # start tracking

View File

@ -221,6 +221,6 @@ def run(cli_args=None, hidraw_path=None):
m.run(c, args, _find_receiver, _find_device)
except AssertionError:
tb_last = extract_tb(_sys.exc_info()[2])[-1]
_sys.exit("%s: assertion failed: %s line %d" % (NAME.lower(), tb_last[0], tb_last[1]))
_sys.exit(f"{NAME.lower()}: assertion failed: {tb_last[0]} line {int(tb_last[1])}")
except Exception:
_sys.exit(f"{NAME.lower()}: error: {format_exc()}")

View File

@ -127,7 +127,7 @@ def run(receivers, args, find_receiver, _ignore):
if receiver.pairing.new_device:
dev = receiver.pairing.new_device
print("Paired device %d: %s (%s) [%s:%s]" % (dev.number, dev.name, dev.codename, dev.wpid, dev.serial))
print(f"Paired device {int(dev.number)}: {dev.name} ({dev.codename}) [{dev.wpid}:{dev.serial}]")
else:
error = receiver.pairing.error
if error:

View File

@ -45,9 +45,9 @@ def _print_receiver(receiver):
for f in receiver.firmware:
print(" %-11s: %s" % (f.kind, f.version))
print(" Has", paired_count, "paired device(s) out of a maximum of %d." % receiver.max_devices)
print(" Has", paired_count, f"paired device(s) out of a maximum of {int(receiver.max_devices)}.")
if receiver.remaining_pairings() and receiver.remaining_pairings() >= 0:
print(" Has %d successful pairing(s) remaining." % receiver.remaining_pairings())
print(f" Has {int(receiver.remaining_pairings())} successful pairing(s) remaining.")
notification_flags = _hidpp10.get_notification_flags(receiver)
if notification_flags is not None:
@ -60,7 +60,7 @@ def _print_receiver(receiver):
activity = receiver.read_register(_hidpp10_constants.REGISTERS.devices_activity)
if activity:
activity = [(d, ord(activity[d - 1 : d])) for d in range(1, receiver.max_devices)]
activity_text = ", ".join(("%d=%d" % (d, a)) for d, a in activity if a > 0)
activity_text = ", ".join(f"{int(d)}={int(a)}" for d, a in activity if a > 0)
print(" Device activity counters:", activity_text or "(empty)")
@ -70,7 +70,7 @@ def _battery_text(level):
elif isinstance(level, _NamedInt):
return str(level)
else:
return "%d%%" % level
return f"{int(level)}%"
def _battery_line(dev):
@ -96,7 +96,7 @@ def _print_device(dev, num=None):
return
if num or dev.number < 8:
print(" %d: %s" % (num or dev.number, dev.name))
print(f" {int(num or dev.number)}: {dev.name}")
else:
print(f"{dev.name}")
print(" Device path :", dev.path)
@ -119,7 +119,7 @@ def _print_device(dev, num=None):
print(" Unit ID: ", dev.unitId)
if dev.firmware:
for fw in dev.firmware:
print(" %11s:" % fw.kind, (fw.name + " " + fw.version).strip())
print(f" {fw.kind:11}:", (fw.name + " " + fw.version).strip())
if dev.power_switch_location:
print(f" The power switch is located on the {dev.power_switch_location}.")
@ -235,7 +235,7 @@ def _print_device(dev, num=None):
response = dev.feature_request(_hidpp20_constants.FEATURE.CONFIG_CHANGE, 0x00)
print(f" Configuration: {response.hex()}")
elif feature == _hidpp20_constants.FEATURE.REMAINING_PAIRING:
print(" Remaining Pairings: %d" % _hidpp20.get_remaining_pairing(dev))
print(f" Remaining Pairings: {int(_hidpp20.get_remaining_pairing(dev))}")
elif feature == _hidpp20_constants.FEATURE.ONBOARD_PROFILES:
if _hidpp20.get_onboard_mode(dev) == _hidpp20_constants.ONBOARD_MODES.MODE_HOST:
mode = "Host"
@ -272,7 +272,7 @@ def _print_device(dev, num=None):
print(" %2d: %-26s, default: %-27s => %-26s" % (k.index, k.key, k.default_task, k.mapped_to))
gmask_fmt = ",".join(k.group_mask)
gmask_fmt = gmask_fmt if gmask_fmt else "empty"
print(" %s, pos:%d, group:%1d, group mask:%s" % (", ".join(k.flags), k.pos, k.group, gmask_fmt))
print(f" {', '.join(k.flags)}, pos:{int(k.pos)}, group:{int(k.group):1}, group mask:{gmask_fmt}")
report_fmt = ", ".join(k.mapping_flags)
report_fmt = report_fmt if report_fmt else "default"
print(f" reporting: {report_fmt}")

View File

@ -33,6 +33,6 @@ def run(receivers, args, find_receiver, find_device):
# query these now, it's last chance to get them
number, codename, wpid, serial = dev.number, dev.codename, dev.wpid, dev.serial
dev.receiver._unpair_device(number, True) # force an unpair
print("Unpaired %d: %s (%s) [%s:%s]" % (number, dev.name, codename, wpid, serial))
print(f"Unpaired {int(number)}: {dev.name} ({codename}) [{wpid}:{serial}]")
except Exception as e:
raise e

View File

@ -85,7 +85,7 @@ def _battery_icon_name(level, charging):
def lux(level=None):
if level is None or level < 0:
return "light_unknown"
return "solaar-light_%03d" % (20 * ((level + 50) // 100))
return f"solaar-light_{int(20 * ((level + 50) // 100)):03}"
_ICON_SETS = {}

View File

@ -555,7 +555,7 @@ def _update_details(button):
flag_names = (
(f"({_('none')})",) if flag_bits == 0 else _hidpp10_constants.NOTIFICATION_FLAG.flag_names(flag_bits)
)
yield (_("Notifications"), ("\n%15s" % " ").join(flag_names))
yield (_("Notifications"), (f"\n{' ':15}").join(flag_names))
def _set_details(text):
_details._text.set_markup(text)
@ -677,7 +677,7 @@ def _update_device_panel(device, panel, buttons, full=False):
if battery_voltage is not None:
panel._battery._label.set_text(_("Battery Voltage"))
text = "%dmV" % battery_voltage
text = f"{int(battery_voltage)}mV"
tooltip_text = _("Voltage reported by battery")
else:
panel._battery._label.set_text(_("Battery Level"))
@ -686,12 +686,12 @@ def _update_device_panel(device, panel, buttons, full=False):
if battery_voltage is not None and battery_level is not None:
text += ", "
if battery_level is not None:
text += _(str(battery_level)) if isinstance(battery_level, _NamedInt) else "%d%%" % battery_level
text += _(str(battery_level)) if isinstance(battery_level, _NamedInt) else f"{int(battery_level)}%"
if battery_next_level is not None and not charging:
if isinstance(battery_next_level, _NamedInt):
text += "<small> (" + _("next reported ") + _(str(battery_next_level)) + ")</small>"
else:
text += "<small> (" + _("next reported ") + ("%d%%" % battery_next_level) + ")</small>"
text += "<small> (" + _("next reported ") + f"{int(battery_next_level)}%" + ")</small>"
tooltip_text = tooltip_text + _(" and next level to be reported.")
if is_online:
if charging:
@ -889,11 +889,11 @@ def update_device(device, item, selected_device_id, need_popup, full=False):
_model.set_value(item, _COLUMN.STATUS_ICON, _CAN_SET_ROW_NONE)
else:
if battery_voltage is not None and False: # Use levels instead of voltage here
status_text = "%(battery_voltage)dmV" % {"battery_voltage": battery_voltage}
status_text = f"{int(battery_voltage)}mV"
elif isinstance(battery_level, _NamedInt):
status_text = _(str(battery_level))
else:
status_text = "%(battery_percent)d%%" % {"battery_percent": battery_level}
status_text = f"{int(battery_level)}%"
_model.set_value(item, _COLUMN.STATUS_TEXT, status_text)
charging = device.battery_info.charging() if device.battery_info is not None else None