From 306d4f29429c75beeaa0f07876277ee2ceb27a49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 17 Mar 2021 15:11:54 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20pre-commit=20with=20new=20settin?= =?UTF-8?q?gs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/comm/connectionprofile.py | 13 ++-- src/octoprint/comm/job/__init__.py | 6 +- src/octoprint/comm/protocol/__init__.py | 28 ++++---- .../comm/protocol/reprap/__init__.py | 72 +++++++++---------- .../comm/protocol/reprap/commands/gcode.py | 4 +- .../comm/protocol/reprap/flavors/__init__.py | 6 +- .../comm/protocol/reprap/flavors/repetier.py | 2 +- .../comm/protocol/reprap/util/__init__.py | 14 ++-- .../comm/protocol/reprap/util/queues.py | 4 +- src/octoprint/comm/transport/__init__.py | 12 ++-- src/octoprint/comm/util/parameters.py | 24 +++---- .../plugins/virtual_printer/__init__.py | 2 +- .../server/api/connection_profiles.py | 14 ++-- tests/comm/__init__.py | 2 +- tests/comm/protocol/__init__.py | 4 +- 15 files changed, 95 insertions(+), 112 deletions(-) diff --git a/src/octoprint/comm/connectionprofile.py b/src/octoprint/comm/connectionprofile.py index 8c248ef94..3c3b4f3e9 100644 --- a/src/octoprint/comm/connectionprofile.py +++ b/src/octoprint/comm/connectionprofile.py @@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os from os import scandir @@ -21,7 +20,7 @@ class ConnectionProfile: protocol_parameters=None, transport=None, transport_parameters=None, - **kwargs + **kwargs, ): self.id = id self.name = name if name is not None else id @@ -61,7 +60,7 @@ class ConnectionProfileManager: def select(self, identifier): self._current = self.get(identifier) if self._current is None: - self._logger.error("Profile {} is invalid, cannot select".format(identifier)) + self._logger.error(f"Profile {identifier} is invalid, cannot select") return False return True @@ -118,7 +117,7 @@ class ConnectionProfileManager: if profile is not None: return profile else: - self._logger.warning("Default profile {} is invalid".format(default)) + self._logger.warning(f"Default profile {default} is invalid") return None @@ -153,7 +152,7 @@ class ConnectionProfileManager: try: profile = self._load_from_path(path) except InvalidProfileError: - self._logger.warning("Profile {} is invalid, skipping".format(identifier)) + self._logger.warning(f"Profile {identifier} is invalid, skipping") continue if profile is None: @@ -181,7 +180,7 @@ class ConnectionProfileManager: import yaml - with io.open(path, "rt", encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: data = yaml.safe_load(f) if data is None or not isinstance(data, dict): @@ -224,7 +223,7 @@ class ConnectionProfileManager: return False def _get_profile_path(self, identifier): - return os.path.join(self._folder, "{}.profile".format(identifier)) + return os.path.join(self._folder, f"{identifier}.profile") class InvalidProfileError(Exception): diff --git a/src/octoprint/comm/job/__init__.py b/src/octoprint/comm/job/__init__.py index b3d3843b5..911bb6a11 100644 --- a/src/octoprint/comm/job/__init__.py +++ b/src/octoprint/comm/job/__init__.py @@ -168,7 +168,7 @@ class Printjob(ProtocolListener, ListenerAware, metaclass=ABCMeta): def report_stats(self): elapsed = self.elapsed if elapsed: - self._logger.info("Job processed in {}s".format(elapsed)) + self._logger.info(f"Job processed in {elapsed}s") def reset_job(self, success=True): self._last_result.progress = 1.0 if success else self.progress @@ -351,9 +351,7 @@ class LocalFilePrintjob(StoragePrintjob): lines = self._read_lines if elapsed and lines: - self._logger.info( - "Job processed in {:.3f}s ({} lines)".format(elapsed, lines) - ) + self._logger.info(f"Job processed in {elapsed:.3f}s ({lines} lines)") class CopyJobMixin: diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index b36363496..dac320b57 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -50,9 +50,9 @@ def register_protocol(protocol_class, settings, path): logger = logging.getLogger(__name__) if not hasattr(protocol_class, "key"): - raise ValueError("Protocol class {} is missing key".format(protocol_class)) + raise ValueError(f"Protocol class {protocol_class} is missing key") if not hasattr(protocol_class, "settings"): - raise ValueError("Protocol class {} is missing settings".format(protocol_class)) + raise ValueError(f"Protocol class {protocol_class} is missing settings") # register settings overlay overlay = register_settings_overlay(settings, path, protocol_class.settings) @@ -309,17 +309,17 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener): self._state = new_state - name = "_on_switching_state_{}".format(new_state) + name = f"_on_switching_state_{new_state}" method = getattr(self, name, None) if method is not None: method(old_state) self.process_protocol_log( - "--- Protocol state changed from '{}' to '{}'".format(old_state, new_state) + f"--- Protocol state changed from '{old_state}' to '{new_state}'" ) self.notify_listeners("on_protocol_state", self, old_state, new_state) - name = "_on_switched_state_{}".format(new_state) + name = f"_on_switched_state_{new_state}" method = getattr(self, name, None) if method is not None: method(old_state) @@ -352,7 +352,7 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener): raise ProtocolAlreadyConnectedError("Already connected, disconnect first") self.process_protocol_log( - "--- Protocol {} connecting via transport {}...".format(self, transport) + f"--- Protocol {self} connecting via transport {transport}..." ) if transport_args is None: @@ -396,7 +396,7 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener): self._transport.disconnect(wait=wait) except Exception: self._logger.exception( - "Error while disconnecting from transport {}".format(self._transport) + f"Error while disconnecting from transport {self._transport}" ) error = True @@ -407,9 +407,7 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener): def process(self, job, position=0, user=None, tags=None, **kwargs): if not job.can_process(self): - raise ValueError( - "Job {} cannot be processed with protocol {}".format(job, self) - ) + raise ValueError(f"Job {job} cannot be processed with protocol {self}") self._job = job self._job.register_listener(self) @@ -452,7 +450,7 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener): self._job, user=user, tags=tags, - **kwargs + **kwargs, ) self._job.cancel(error=error, user=user, tags=tags, **kwargs) @@ -515,21 +513,21 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener): message = to_unicode(data, errors="replace").strip() self.notify_listeners("on_protocol_log_received", self, message) - message = "<<< {}".format(message) + message = f"<<< {message}" self.process_protocol_log(message) def on_transport_log_sent_data(self, transport, data): message = to_unicode(data, errors="replace").strip() self.notify_listeners("on_protocol_log_sent", self, message) - message = ">>> {}".format(message) + message = f">>> {message}" self.process_protocol_log(message) def on_transport_log_message(self, transport, data): message = to_unicode(data, errors="replace").strip() self.notify_listeners("on_protocol_log_message", self, message) - message = "--- {}".format(message) + message = f"--- {message}" self.process_protocol_log(message) def process_protocol_log(self, message): @@ -622,7 +620,7 @@ class Fdm3dPrinterProtocolMixin( feedrate=None, relative=False, *args, - **kwargs + **kwargs, ): pass diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py index 344a5804b..d6786cec1 100644 --- a/src/octoprint/comm/protocol/reprap/__init__.py +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -1163,7 +1163,7 @@ class ReprapGcodeProtocol( feedrate=None, relative=False, *args, - **kwargs + **kwargs, ): tags = kwargs.pop("tags", set()) | {"trigger:protocol.move"} @@ -1206,7 +1206,7 @@ class ReprapGcodeProtocol( tool = int(heater[len("tool") :]) except ValueError: self._logger.error( - "Got invalid tool heater, expected tool, got: {}".format(heater) + f"Got invalid tool heater, expected tool, got: {heater}" ) return command = self.flavor.command_set_extruder_temp( @@ -1218,7 +1218,7 @@ class ReprapGcodeProtocol( command = self.flavor.command_set_chamber_temp(temperature, wait=wait) else: self._logger.warning( - "Got unknown heater identifier to set temperature on: {}".format(heater) + f"Got unknown heater identifier to set temperature on: {heater}" ) return @@ -1260,7 +1260,7 @@ class ReprapGcodeProtocol( self.flavor.command_sd_set_pos(position), self.flavor.command_sd_start(), tags=tags, - **kwargs + **kwargs, ) def pause_file_print(self, *args, **kwargs): @@ -1328,7 +1328,7 @@ class ReprapGcodeProtocol( def reset_linenumber(self, linenumber=0): with self._line_mutex: self._logger.info( - "M110 detected, setting current line number to {}".format(linenumber) + f"M110 detected, setting current line number to {linenumber}" ) # send M110 command with new line number @@ -1469,7 +1469,7 @@ class ReprapGcodeProtocol( ) # prefix, postfix [ , variables [ , additional tags ] ] except Exception: self._logger.exception( - "Error while processing hook {}.".format(name), + f"Error while processing hook {name}.", extra={"plugin": name}, ) else: @@ -1493,7 +1493,7 @@ class ReprapGcodeProtocol( variables = retval[2] context.update({"plugins": {name: variables}}) - additional_tags = {"plugin:{}".format(name)} + additional_tags = {f"plugin:{name}"} if len(retval) == 4: # additional tags are defined additional_tags |= set(retval[3]) @@ -1518,10 +1518,10 @@ class ReprapGcodeProtocol( tags={ "trigger:protocol.send_script", "source:script", - "script:{}".format(script.name), + f"script:{script.name}", }, part_of_job=part_of_job, - *lines + *lines, ) def repair(self, *args, **kwargs): @@ -1779,7 +1779,7 @@ class ReprapGcodeProtocol( self._on_comm_any(line, lower_line) for message in self._current_registered_messages: - handler_method = getattr(self, "_on_{}".format(message), None) + handler_method = getattr(self, f"_on_{message}", None) if not handler_method: # no handler, nothing to do continue @@ -1794,7 +1794,7 @@ class ReprapGcodeProtocol( if matches: message_args = {} - parse_method = getattr(self.flavor, "parse_{}".format(message), None) + parse_method = getattr(self.flavor, f"parse_{message}", None) if parse_method: # flavor specific parser? run it parse_result = parse_method(line, lower_line) @@ -1808,7 +1808,7 @@ class ReprapGcodeProtocol( message_args.update(parse_result) # before handler: flavor.before_comm_* or flavor.before_message_* - before_handler = getattr(self.flavor, "before_{}".format(message), None) + before_handler = getattr(self.flavor, f"before_{message}", None) if before_handler: before_handler(**message_args) @@ -1816,7 +1816,7 @@ class ReprapGcodeProtocol( result = handler_method(**message_args) # after handler: flavor.after_comm_* or flavor.after_message_* - after_handler = getattr(self.flavor, "after_{}".format(message), None) + after_handler = getattr(self.flavor, f"after_{message}", None) if after_handler: after_handler(result, **message_args) @@ -2026,7 +2026,7 @@ class ReprapGcodeProtocol( def _on_comm_ignore_ok(self): self.internal_state.ignore_ok += 1 self._logger.info( - "Ignoring next ok, counter is now at {}".format(self.internal_state.ignore_ok) + f"Ignoring next ok, counter is now at {self.internal_state.ignore_ok}" ) def _on_comm_wait(self): @@ -2175,14 +2175,14 @@ class ReprapGcodeProtocol( def _on_comm_error(self, line, lower_line, error): for message in self._error_messages: - handler_method = getattr(self, "_on_{}".format(message), None) + handler_method = getattr(self, f"_on_{message}", None) if not handler_method: continue if getattr(self.flavor, message)(line, lower_line, error): message_args = {} - parse_method = getattr(self.flavor, "parse_{}".format(message), None) + parse_method = getattr(self.flavor, f"parse_{message}", None) if parse_method: parse_result = parse_method(line, lower_line, error) if parse_result is None: @@ -2305,7 +2305,7 @@ class ReprapGcodeProtocol( self.internal_state.heatup_start = time.monotonic() shared_nozzle = self._printer_profile["extruder"]["sharedNozzle"] - current_tool_key = "T{}".format(self.internal_state.current_tool) + current_tool_key = f"T{self.internal_state.current_tool}" for name, hook in self._temperature_hooks.items(): try: @@ -2314,13 +2314,13 @@ class ReprapGcodeProtocol( return except Exception: self._logger.exception( - "Error while processing temperatures in {}, skipping".format(name), + f"Error while processing temperatures in {name}, skipping", extra={"plugin": name}, ) if current_tool_key in temperatures: for x in range(max_tool_num + 1): - tool = "T{}".format(x) + tool = f"T{x}" if tool not in temperatures: if shared_nozzle: # replicate the current temperature across all tools (see #2077) @@ -2361,7 +2361,7 @@ class ReprapGcodeProtocol( else: # multiple extruder coordinates provided, find current one self.last_position.e = ( - position.get("e{}".format(self.internal_state.current_tool)) + position.get(f"e{self.internal_state.current_tool}") if t_and_f_trustworthy else None ) @@ -2402,7 +2402,7 @@ class ReprapGcodeProtocol( ) if not self.internal_state.firmware_identified and firmware_name: - self._logger.info('Printer reports firmware name "{}"'.format(firmware_name)) + self._logger.info(f'Printer reports firmware name "{firmware_name}"') for flavor_class in all_flavors(): if ( @@ -2427,7 +2427,7 @@ class ReprapGcodeProtocol( hook(self, firmware_name, copy.copy(data)) except Exception: self._logger.exception( - "Error processing firmware info hook {}:".format(name), + f"Error processing firmware info hook {name}:", extra={"plugin": name}, ) @@ -2461,7 +2461,7 @@ class ReprapGcodeProtocol( ) except Exception: self._logger.exception( - "Error processing firmware capability hook {}:".format(name), + f"Error processing firmware capability hook {name}:", extra={"plugin": name}, ) @@ -2696,9 +2696,9 @@ class ReprapGcodeProtocol( line, tags={ "source:file", - "filepos:{}".format(pos), - "fileline:{}".format(read_lines), - "fileactualline:{}".format(actual_lines), + f"filepos:{pos}", + f"fileline:{read_lines}", + f"fileactualline:{actual_lines}", }, ) if self._send_command(command): @@ -2868,7 +2868,7 @@ class ReprapGcodeProtocol( ) return True except TypeAlreadyInQueue as e: - self._logger.debug("Type already in queue: {}".format(e.type)) + self._logger.debug(f"Type already in queue: {e.type}") return False def _send_loop(self): @@ -3012,7 +3012,7 @@ class ReprapGcodeProtocol( def _log_command_phase(self, phase, command): if self._phase_logger.isEnabledFor(logging.DEBUG): - self._phase_logger.debug("phase: {}, command: {!r}".format(phase, command)) + self._phase_logger.debug(f"phase: {phase}, command: {command!r}") def _process_command_phase(self, phase, command, **kwargs): command = to_command(command, **kwargs) @@ -3056,8 +3056,8 @@ class ReprapGcodeProtocol( hook_results, tags_to_add={ "source:rewrite", - "phase:{}".format(phase), - "plugin:{}".format(name), + f"phase:{phase}", + f"plugin:{name}", }, ) @@ -3131,7 +3131,7 @@ class ReprapGcodeProtocol( ) # trigger built-in handler if available - atcommand_handler = "_atcommand_{}_{}".format(command.atcommand, phase) + atcommand_handler = f"_atcommand_{command.atcommand}_{phase}" if atcommand_handler in self._atcommand_handlers: try: getattr(self, atcommand_handler)(command) @@ -3276,7 +3276,7 @@ class ReprapGcodeProtocol( self._trigger_emergency_stop() return (None,) else: - message = "Force-sending {} to the printer".format(command) + message = f"Force-sending {command} to the printer" self._logger.info(message) return self._emergency_force_send(command, message) @@ -3284,7 +3284,7 @@ class ReprapGcodeProtocol( self.state in ProtocolState.PROCESSING_STATES and command.code in self.flavor.pausing_commands ): - self._logger.info("Pausing print job due to command {}".format(command)) + self._logger.info(f"Pausing print job due to command {command}") self.pause_processing(tags=command.tags) if command.code in self.flavor.blocked_commands: @@ -3358,7 +3358,7 @@ class ReprapGcodeProtocol( def _to_logfile_with_terminal(self, message=None, level=logging.INFO): log = "Last lines in terminal:\n" + "\n".join( - map(lambda x: "| {}".format(x), list(self._terminal_log)) + map(lambda x: f"| {x}", list(self._terminal_log)) ) if message is not None: log = message + "\n| " + log @@ -3400,9 +3400,7 @@ class ReprapGcodeProtocol( def _trigger_emergency_stop(self, close=True): emergency_command = self.flavor.command_emergency_stop() - self._logger.info( - "Force-sending {} to the printer".format(emergency_command.code) - ) + self._logger.info(f"Force-sending {emergency_command.code} to the printer") # emergency stop, jump the queue with the M112, regardless of whether the EMERGENCY_PARSER capability is # available or not diff --git a/src/octoprint/comm/protocol/reprap/commands/gcode.py b/src/octoprint/comm/protocol/reprap/commands/gcode.py index b8fe1c837..c187e9319 100644 --- a/src/octoprint/comm/protocol/reprap/commands/gcode.py +++ b/src/octoprint/comm/protocol/reprap/commands/gcode.py @@ -130,7 +130,7 @@ class GcodeCommand(Command): def __getattr__(self, item): if len(item) == 1: return self.args.get(item, None) - raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item)) + raise AttributeError(f"'GcodeCommand' object has no attribute '{item}'") def __repr__(self): return self._repr @@ -143,7 +143,7 @@ class GcodeCommand(Command): if value is True: attr.append(key.upper()) else: - attr.append("{}{!r}".format(key.upper(), value)) + attr.append(f"{key.upper()}{value!r}") attribute_str = " ".join(attr) return "{}{}{}".format( self.code.upper(), diff --git a/src/octoprint/comm/protocol/reprap/flavors/__init__.py b/src/octoprint/comm/protocol/reprap/flavors/__init__.py index 47655e3bf..052753aa9 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/__init__.py +++ b/src/octoprint/comm/protocol/reprap/flavors/__init__.py @@ -118,9 +118,7 @@ class StandardFlavor(metaclass=FlavorMeta): * ``target``: target temperature, if provided (float) """ - regex_position = re.compile( - r"(?P[XYZE]):(?P{float})\s*".format(float=regex_float_pattern) - ) + regex_position = re.compile(fr"(?P[XYZE]):(?P{regex_float_pattern})\s*") """Regex for matching position entries in line. Groups will be as follows: @@ -713,7 +711,7 @@ class StandardFlavor(metaclass=FlavorMeta): tool_num = self._protocol.internal_state.current_tool return self._apply_temperature_offset( - "tool{}".format(tool_num), command, support_r=support_r + f"tool{tool_num}", command, support_r=support_r ) def handle_gcode_M104_sent(self, command, wait=False, support_r=False): diff --git a/src/octoprint/comm/protocol/reprap/flavors/repetier.py b/src/octoprint/comm/protocol/reprap/flavors/repetier.py index 9da4b4974..603e78138 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/repetier.py +++ b/src/octoprint/comm/protocol/reprap/flavors/repetier.py @@ -60,7 +60,7 @@ class RepetierFlavor(StandardFlavor): if match is not None: tool_num = int(match.group("toolnum")) target = float(match.group("target")) - tool = "T{}".format(tool_num) + tool = f"T{tool_num}" temperatures = {} temperatures[tool] = (None, target) return { diff --git a/src/octoprint/comm/protocol/reprap/util/__init__.py b/src/octoprint/comm/protocol/reprap/util/__init__.py index 44156c97b..fafd51279 100644 --- a/src/octoprint/comm/protocol/reprap/util/__init__.py +++ b/src/octoprint/comm/protocol/reprap/util/__init__.py @@ -263,27 +263,23 @@ class PositionRecord: return True def __init__(self, *args, **kwargs): - attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)]) + attrs = self._standard_attrs | {key for key in kwargs if self.valid_e(key)} for attr in attrs: setattr(self, attr, kwargs.get(attr)) def copy_from(self, other): # make sure all standard attrs and attrs from other are set - attrs = self._standard_attrs | set( - [key for key in dir(other) if self.valid_e(key)] - ) + attrs = self._standard_attrs | {key for key in dir(other) if self.valid_e(key)} for attr in attrs: setattr(self, attr, getattr(other, attr)) # delete attrs other doesn't have - attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs + attrs = {key for key in dir(self) if self.valid_e(key)} - attrs for attr in attrs: delattr(self, attr) def as_dict(self): - attrs = self._standard_attrs | set( - [key for key in dir(self) if self.valid_e(key)] - ) + attrs = self._standard_attrs | {key for key in dir(self) if self.valid_e(key)} return {attr: getattr(self, attr) for attr in attrs} @@ -327,7 +323,7 @@ class TemperatureRecord: tools = self.tools for tool, data in tools.items(): - result["tool{}".format(tool)] = {"actual": data[0], "target": data[1]} + result[f"tool{tool}"] = {"actual": data[0], "target": data[1]} bed = self.bed result["bed"] = {"actual": bed[0], "target": bed[1]} diff --git a/src/octoprint/comm/protocol/reprap/util/queues.py b/src/octoprint/comm/protocol/reprap/util/queues.py index b1719b023..e8e9ee657 100644 --- a/src/octoprint/comm/protocol/reprap/util/queues.py +++ b/src/octoprint/comm/protocol/reprap/util/queues.py @@ -124,7 +124,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -139,7 +139,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) diff --git a/src/octoprint/comm/transport/__init__.py b/src/octoprint/comm/transport/__init__.py index 71d9b0cfa..f784580c5 100644 --- a/src/octoprint/comm/transport/__init__.py +++ b/src/octoprint/comm/transport/__init__.py @@ -53,7 +53,7 @@ def register_transport(transport_class, settings, path): logger = logging.getLogger(__name__) if not hasattr(transport_class, "key"): - raise ValueError("Transport class {} is missing key".format(transport_class)) + raise ValueError(f"Transport class {transport_class} is missing key") # register settings overlay overlay = register_transport_overlay(transport_class, settings, path) @@ -74,9 +74,9 @@ def register_transport(transport_class, settings, path): def register_transport_overlay(transport_class, settings, path): if not hasattr(transport_class, "key"): - raise ValueError("Transport class {} is missing key".format(transport_class)) + raise ValueError(f"Transport class {transport_class} is missing key") if not hasattr(transport_class, "settings"): - raise ValueError("Transport class {} is missing settings".format(transport_class)) + raise ValueError(f"Transport class {transport_class} is missing settings") params = transport_class.settings return register_settings_overlay(settings, path + [transport_class.key], params) @@ -161,7 +161,7 @@ class Transport(ListenerAware): self.notify_listeners( "on_transport_log_message", self, - "Transport state changed from '{}' to '{}'".format(old_state, value), + f"Transport state changed from '{old_state}' to '{value}'", ) def connect(self, **params): @@ -343,7 +343,7 @@ class LineAwareTransportWrapper(SeparatorAwareTransportWrapper): SeparatorAwareTransportWrapper.__init__(self, transport, b"\n") def __str__(self): - return "LineAwareTransportWrapper({})".format(self.transport) + return f"LineAwareTransportWrapper({self.transport})" class PushingTransportWrapper(TransportWrapper): @@ -392,7 +392,7 @@ class PushingTransportWrapper(TransportWrapper): raise def __str__(self): - return "PushingTransportWrapper({})".format(self.transport) + return f"PushingTransportWrapper({self.transport})" class TransportListener: diff --git a/src/octoprint/comm/util/parameters.py b/src/octoprint/comm/util/parameters.py index c79188c77..ca3e4d6c3 100644 --- a/src/octoprint/comm/util/parameters.py +++ b/src/octoprint/comm/util/parameters.py @@ -84,10 +84,10 @@ class ParamType: def __repr__(self): return ( - "{}(".format(self.__class__.__name__) + f"{self.__class__.__name__}(" + ", ".join( [ - "{}={!r}".format(key, value) + f"{key}={value!r}" for key, value in self.__dict__.items() if not key.startswith("_") ] @@ -127,15 +127,13 @@ class IntegerType(ParamType): try: value = int(value) except ValueError: - raise ValueError("value {!r} is not a valid integer".format(value)) + raise ValueError(f"value {value!r} is not a valid integer") if self.min is not None and value < self.min: - raise ValueError( - "value {} is less than minimum valid value {}".format(value, self.min) - ) + raise ValueError(f"value {value} is less than minimum valid value {self.min}") if self.max is not None and value > self.max: raise ValueError( - "value {} is greater than maximum valid value {}".format(value, self.max) + f"value {value} is greater than maximum valid value {self.max}" ) return value @@ -159,15 +157,13 @@ class FloatType(ParamType): try: value = float(value) except ValueError: - raise ValueError("value {!r} is not a valid float".format(value)) + raise ValueError(f"value {value!r} is not a valid float") if self.min is not None and value < self.min: - raise ValueError( - "value {} is less than minimum valid value {}".format(value, self.min) - ) + raise ValueError(f"value {value} is less than minimum valid value {self.min}") if self.max is not None and value > self.max: raise ValueError( - "value {} is greater than maximum valid value {}".format(value, self.max) + f"value {value} is greater than maximum valid value {self.max}" ) return value @@ -180,7 +176,7 @@ class BooleanType(ParamType): try: value = bool(value) except ValueError: - raise ValueError("value {!r} is not a valid boolean".format(value)) + raise ValueError(f"value {value!r} is not a valid boolean") return value @@ -283,7 +279,7 @@ class ParamGroup(ParamType): def convert(self, value): if not isinstance(value, dict): - raise ValueError("value {!r} must be a dict".format(value)) + raise ValueError(f"value {value!r} must be a dict") return {k: v.convert() for k, v in value.items()} diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index a1a17c25a..6f0915d73 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -16,7 +16,7 @@ class VirtualSerialTransport(SerialTransport): @classmethod def with_settings_and_data(cls, settings, datafolder): return type( - "{}WithSettingsAndData".format(cls.__name__), + f"{cls.__name__}WithSettingsAndData", (cls,), {"settings": settings, "datafolder": datafolder}, ) diff --git a/src/octoprint/server/api/connection_profiles.py b/src/octoprint/server/api/connection_profiles.py index 719c32e14..c6935c724 100644 --- a/src/octoprint/server/api/connection_profiles.py +++ b/src/octoprint/server/api/connection_profiles.py @@ -54,7 +54,7 @@ def connectionProfilesList(): def connectionProfilesGet(identifier): profile = connectionProfileManager.get(identifier) if profile is None: - return make_response("Unknown profile: {}".format(identifier), 404) + return make_response(f"Unknown profile: {identifier}", 404) else: return jsonify({"profile": _convert_profile(profile)}) @@ -96,10 +96,10 @@ def connectionProfileSet(identifier): except InvalidProfileError: return make_response("Profile is invalid", 400) except SaveError: - return make_response("Profile {} could not be saved".format(profile.id), 400) + return make_response(f"Profile {profile.id} could not be saved", 400) except Exception as e: return make_response( - "Could not save profile due to an unexpected error: {}".format(e), 500 + f"Could not save profile due to an unexpected error: {e}", 500 ) else: return jsonify({"profile": _convert_profile(profile)}) @@ -112,12 +112,12 @@ def connectionProfilesDelete(identifier): current_profile = connectionProfileManager.get_current() if current_profile and current_profile.id == identifier: return make_response( - "Cannot delete currently selected profile: {}".format(identifier), 409 + f"Cannot delete currently selected profile: {identifier}", 409 ) default_profile = connectionProfileManager.get_default() if default_profile and default_profile.id == identifier: - return make_response("Cannot delete default profile: {}".format(identifier), 409) + return make_response(f"Cannot delete default profile: {identifier}", 409) connectionProfileManager.remove(identifier) return NO_CONTENT @@ -159,10 +159,10 @@ def connectionProfilesUpdate(identifier): except InvalidProfileError: return make_response("Profile is invalid", 400) except SaveError: - return make_response("Profile {} could not be saved".format(profile.id), 400) + return make_response(f"Profile {profile.id} could not be saved", 400) except Exception as e: return make_response( - "Could not save profile due to an unexpected error: {}".format(e), 500 + f"Could not save profile due to an unexpected error: {e}", 500 ) else: return jsonify({"profile": _convert_profile(saved_profile)}) diff --git a/tests/comm/__init__.py b/tests/comm/__init__.py index e2ec39f45..824982e35 100644 --- a/tests/comm/__init__.py +++ b/tests/comm/__init__.py @@ -69,7 +69,7 @@ class TestTransport(Transport): expected = expected() if expected != actual: - raise AssertionError("Expected {!r}, got {!r}".format(expected, actual)) + raise AssertionError(f"Expected {expected!r}, got {actual!r}") return actual diff --git a/tests/comm/protocol/__init__.py b/tests/comm/protocol/__init__.py index 35e9c0975..6738a1da2 100644 --- a/tests/comm/protocol/__init__.py +++ b/tests/comm/protocol/__init__.py @@ -7,9 +7,9 @@ __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms import unittest +from unittest import mock import ddt -import mock import octoprint.comm.protocol.reprap from octoprint.util import to_bytes @@ -83,7 +83,7 @@ class RepRapProtocolTest(unittest.TestCase): if capabilities is None: capabilities = {} - firmware_info = "FIRMWARE_NAME:{}\n".format(firmware_name) + firmware_info = f"FIRMWARE_NAME:{firmware_name}\n" for cap, enabled in capabilities.items(): firmware_info += "Cap:{}:{}\n".format(cap.upper(), "1" if enabled else "0") firmware_info += "ok\n"