Skip to content

Commit

Permalink
Switch to fstrings (#260)
Browse files Browse the repository at this point in the history
  • Loading branch information
ol-iver authored Aug 19, 2023
1 parent a3d269c commit 208fd3c
Show file tree
Hide file tree
Showing 11 changed files with 109 additions and 154 deletions.
36 changes: 17 additions & 19 deletions denonavr/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,7 @@ async def async_get(
# Use default port of the receiver if no different port is specified
port = port if port is not None else self.port

endpoint = "http://{host}:{port}{request}".format(
host=self.host, port=port, request=request
)
endpoint = f"http://{self.host}:{port}{request}"

client = self.async_client_getter()
try:
Expand All @@ -158,9 +156,7 @@ async def async_post(
# Use default port of the receiver if no different port is specified
port = port if port is not None else self.port

endpoint = "http://{host}:{port}{request}".format(
host=self.host, port=port, request=request
)
endpoint = f"http://{self.host}:{port}{request}"

client = self.async_client_getter()
try:
Expand Down Expand Up @@ -225,7 +221,7 @@ async def async_post_appcommand(
def add_appcommand_update_tag(self, tag: AppCommandCmd) -> None:
"""Add appcommand tag for full update."""
if tag.cmd_id != "1":
raise ValueError("cmd_id is {} but must be 1".format(tag.cmd_id))
raise ValueError(f"cmd_id is {tag.cmd_id} but must be 1")

# Remove response pattern from tag because it is not relevant for query
tag = attr.evolve(tag, response_pattern=tuple())
Expand All @@ -237,7 +233,7 @@ def add_appcommand_update_tag(self, tag: AppCommandCmd) -> None:
def add_appcommand0300_update_tag(self, tag: AppCommandCmd) -> None:
"""Add appcommand0300 tag for full update."""
if tag.cmd_id != "3":
raise ValueError("cmd_id is {} but must be 3".format(tag.cmd_id))
raise ValueError(f"cmd_id is {tag.cmd_id} but must be 3")

# Remove response pattern from tag because it is not relevant for query
tag = attr.evolve(tag, response_pattern=tuple())
Expand Down Expand Up @@ -271,16 +267,20 @@ def add_query_tags_to_result(
"""
if len(cmd_list) != len(xml_root):
raise AvrIncompleteResponseError(
"Invalid length of response XML. Query has {} elements, "
"response {}".format(len(cmd_list), len(xml_root)),
(
"Invalid length of response XML. Query has"
f" {len(cmd_list)} elements, response {len(xml_root)}"
),
request,
)

for i, child in enumerate(xml_root):
if child.tag not in ["cmd", "error"]:
raise AvrInvalidResponseError(
'Returned document contains a tag other than "cmd" and '
'"error": {}'.format(child.tag),
(
'Returned document contains a tag other than "cmd" and'
f' "error": {child.tag}'
),
request,
)
# Find corresponding attributes from request XML if set and add
Expand Down Expand Up @@ -460,21 +460,19 @@ async def _async_establish_connection(self) -> None:
)
except asyncio.TimeoutError as err:
_LOGGER.debug("%s: Timeout exception on telnet connect", self.host)
raise AvrTimoutError(
"TimeoutException: {}".format(err), "telnet connect"
) from err
raise AvrTimoutError(f"TimeoutException: {err}", "telnet connect") from err
except ConnectionRefusedError as err:
_LOGGER.debug(
"%s: Connection refused on telnet connect", self.host, exc_info=True
)
raise AvrNetworkError(
"ConnectionRefusedError: {}".format(err), "telnet connect"
f"ConnectionRefusedError: {err}", "telnet connect"
) from err
except (OSError, IOError) as err:
_LOGGER.debug(
"%s: Connection failed on telnet reconnect", self.host, exc_info=True
)
raise AvrNetworkError("OSError: {}".format(err), "telnet connect") from err
raise AvrNetworkError(f"OSError: {err}", "telnet connect") from err
_LOGGER.debug("%s: telnet connection complete", self.host)
self._protocol = cast(DenonAVRTelnetProtocol, transport_protocol[1])
self._connection_enabled = True
Expand Down Expand Up @@ -572,7 +570,7 @@ def register_callback(
"""Register a callback handler for an event type."""
# Validate the passed in type
if event != ALL_TELNET_EVENTS and event not in TELNET_EVENTS:
raise ValueError("{} is not a valid callback type.".format(event))
raise ValueError(f"{event} is not a valid callback type.")

if event not in self._callbacks.keys():
self._callbacks[event] = []
Expand Down Expand Up @@ -671,7 +669,7 @@ def send_commands(self, *commands: str) -> bool:
if not self.healthy:
return False
for command in commands:
self._protocol.write("{}\r".format(command))
self._protocol.write(f"{command}\r")
return True

##############
Expand Down
16 changes: 5 additions & 11 deletions denonavr/audyssey.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,9 @@ async def _async_set_audyssey(self, cmd: AppCommandCmd) -> None:

try:
if res.find("cmd").text != "OK":
raise AvrProcessingError(
"SetAudyssey command {} failed".format(cmd.name)
)
raise AvrProcessingError(f"SetAudyssey command {cmd.name} failed")
except AttributeError as err:
raise AvrProcessingError(
"SetAudyssey command {} failed".format(cmd.name)
) from err
raise AvrProcessingError(f"SetAudyssey command {cmd.name} failed") from err

##############
# Properties #
Expand Down Expand Up @@ -198,7 +194,7 @@ async def async_set_multieq(self, value: str) -> None:
"""Set MultiEQ mode."""
setting = MULTI_EQ_MAP_LABELS.get(value)
if setting is None:
raise AvrCommandError("Value {} not known for MultiEQ".format(value))
raise AvrCommandError(f"Value {value} not known for MultiEQ")
cmd = attr.evolve(
AppCommands.SetAudysseyMultiEQ,
param_list=(AppCommandCmdParam(name="multeq", text=setting),),
Expand All @@ -214,9 +210,7 @@ async def async_set_reflevoffset(self, value: str) -> None:
)
setting = REF_LVL_OFFSET_MAP_LABELS.get(value)
if setting is None:
raise AvrCommandError(
"Value {} not known for Reference level offset".format(value)
)
raise AvrCommandError(f"Value {value} not known for Reference level offset")
cmd = attr.evolve(
AppCommands.SetAudysseyReflevoffset,
param_list=(AppCommandCmdParam(name="reflevoffset", text=setting),),
Expand All @@ -227,7 +221,7 @@ async def async_set_dynamicvol(self, value: str) -> None:
"""Set Dynamic Volume."""
setting = DYNAMIC_VOLUME_MAP_LABELS.get(value)
if setting is None:
raise AvrCommandError("Value {} not known for Dynamic Volume".format(value))
raise AvrCommandError(f"Value {value} not known for Dynamic Volume")
cmd = attr.evolve(
AppCommands.SetAudysseyDynamicvol,
param_list=(AppCommandCmdParam(name="dynamicvol", text=setting),),
Expand Down
24 changes: 8 additions & 16 deletions denonavr/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,32 +48,26 @@ async def wrapper(*args, **kwargs):
_LOGGER.debug("HTTP status error on request %s", err.request, exc_info=True)
# Separate handling of 403 errors
if err.response.status_code == 403:
raise AvrForbiddenError(
"HTTPStatusError: {}".format(err), err.request
) from err
raise AvrRequestError(
"HTTPStatusError: {}".format(err), err.request
) from err
raise AvrForbiddenError(f"HTTPStatusError: {err}", err.request) from err
raise AvrRequestError(f"HTTPStatusError: {err}", err.request) from err
except httpx.TimeoutException as err:
_LOGGER.debug(
"HTTP timeout exception on request %s", err.request, exc_info=True
)
raise AvrTimoutError(
"TimeoutException: {}".format(err), err.request
) from err
raise AvrTimoutError(f"TimeoutException: {err}", err.request) from err
except httpx.NetworkError as err:
_LOGGER.debug(
"Network error exception on request %s", err.request, exc_info=True
)
raise AvrNetworkError("NetworkError: {}".format(err), err.request) from err
raise AvrNetworkError(f"NetworkError: {err}", err.request) from err
except httpx.RemoteProtocolError as err:
_LOGGER.debug(
"Remote protocol error exception on request %s",
err.request,
exc_info=True,
)
raise AvrInvalidResponseError(
"RemoteProtocolError: {}".format(err), err.request
f"RemoteProtocolError: {err}", err.request
) from err
except (
ET.ParseError,
Expand All @@ -85,7 +79,7 @@ async def wrapper(*args, **kwargs):
"Defusedxml parse error on request %s", (args, kwargs), exc_info=True
)
raise AvrInvalidResponseError(
"XMLParseError: {}".format(err), (args, kwargs)
f"XMLParseError: {err}", (args, kwargs)
) from err

return wrapper
Expand Down Expand Up @@ -141,13 +135,11 @@ def run_async_synchronously(async_func: Coroutine) -> Callable:
def decorator(func: Callable):
# Check if function is a coroutine
if not inspect.iscoroutinefunction(async_func):
raise AttributeError(
"Function {} is not a coroutine function".format(async_func)
)
raise AttributeError(f"Function {async_func} is not a coroutine function")
# Check if the signature of both functions is equal
if inspect.signature(func) != inspect.signature(async_func):
raise AttributeError(
"Functions {} and {} have different signatures".format(func, async_func)
f"Functions {func} and {async_func} have different signatures"
)

@wraps(func)
Expand Down
2 changes: 1 addition & 1 deletion denonavr/denonavr.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def create_zones(self, add_zones):
# Name either set explicitly or name of Main Zone with suffix
zonename = None
if zname is None and self._name is not None:
zonename = "{} {}".format(self._name, zone)
zonename = f"{self._name} {zone}"
zone_device = attr.evolve(self._device, zone=zone)
zone_inst = DenonAVR(
host=self._host,
Expand Down
56 changes: 27 additions & 29 deletions denonavr/foundation.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def __attrs_post_init__(self) -> None:
self.telnet_commands = ZONE3_TELNET_COMMANDS
self.urls = ZONE3_URLS
else:
raise ValueError("Invalid zone {}".format(self.zone))
raise ValueError(f"Invalid zone {self.zone}")

async def _async_power_callback(
self, zone: str, event: str, parameter: str
Expand Down Expand Up @@ -207,8 +207,10 @@ async def async_identify_receiver(self) -> None:

except AvrRequestError as err:
_LOGGER.debug(
"Request error on port %s when identifying receiver, "
"device is not a %s receivers",
(
"Request error on port %s when identifying receiver, "
"device is not a %s receivers"
),
r_type.port,
r_type.type,
exc_info=err,
Expand Down Expand Up @@ -369,9 +371,7 @@ async def async_get_device_info(self) -> None:
"""Get device information."""
port = DESCRIPTION_TYPES[self.receiver.type].port
command = DESCRIPTION_TYPES[self.receiver.type].url
url = "http://{host}:{port}{command}".format(
host=self.api.host, port=port, command=command
)
url = f"http://{self.api.host}:{port}{command}"

device_info = None
try:
Expand All @@ -384,8 +384,10 @@ async def async_get_device_info(self) -> None:
raise
except AvrRequestError as err:
_LOGGER.error(
"During DenonAVR device identification, when trying to request"
" %s the following error occurred: %s",
(
"During DenonAVR device identification, when trying to request"
" %s the following error occurred: %s"
),
url,
err,
)
Expand All @@ -397,9 +399,11 @@ async def async_get_device_info(self) -> None:
self.model_name = "Unknown"
self.serial_number = None
_LOGGER.warning(
"Unable to get device information of host %s, Device might be "
"in a corrupted state. Continuing without device information. "
"Disconnect and reconnect power to the device and try again.",
(
"Unable to get device information of host %s, Device might be "
"in a corrupted state. Continuing without device information. "
"Disconnect and reconnect power to the device and try again."
),
self.api.host,
)
return
Expand Down Expand Up @@ -447,14 +451,12 @@ async def async_update_power_appcommand(

# Search for power tag
power_tag = xml.find(
"./cmd[@{attribute}='{cmd}']/{zone}".format(
attribute=APPCOMMAND_CMD_TEXT, cmd=power_appcommand.cmd_text, zone=zone
)
f"./cmd[@{APPCOMMAND_CMD_TEXT}='{power_appcommand.cmd_text}']/{zone}"
)

if power_tag is None:
raise AvrProcessingError(
"Power attribute of zone {} not found on update".format(self.zone)
f"Power attribute of zone {self.zone} not found on update"
)

self._power = power_tag.text
Expand All @@ -468,7 +470,7 @@ async def async_update_power_status_xml(
if self.zone == MAIN_ZONE:
urls.append(self.urls.mainzone)
else:
urls.append("{}?ZoneName={}".format(self.urls.mainzone, self.zone))
urls.append(f"{self.urls.mainzone}?ZoneName={self.zone}")
# Tags in XML which might contain information about zones power status
# ordered by their priority
tags = ["./ZonePower/value", "./Power/value"]
Expand All @@ -490,7 +492,7 @@ async def async_update_power_status_xml(
return

raise AvrProcessingError(
"Power attribute of zone {} not found on update".format(self.zone)
f"Power attribute of zone {self.zone} not found on update"
)

##############
Expand Down Expand Up @@ -617,9 +619,8 @@ async def async_update_attrs_appcommand(
# Check if each attribute was updated
if update_attrs and not ignore_missing_response:
raise AvrProcessingError(
"Some attributes of zone {} not found on update: {}".format(
self._device.zone, update_attrs
)
f"Some attributes of zone {self._device.zone} not found on update:"
f" {update_attrs}"
)
if update_attrs and ignore_missing_response:
_LOGGER.debug(
Expand Down Expand Up @@ -685,9 +686,8 @@ async def async_update_attrs_status_xml(
# Check if each attribute was updated
if update_attrs and not ignore_missing_response:
raise AvrProcessingError(
"Some attributes of zone {} not found on update: {}".format(
self._device.zone, update_attrs
)
f"Some attributes of zone {self._device.zone} not found on update:"
f" {update_attrs}"
)

@staticmethod
Expand All @@ -701,17 +701,15 @@ def create_appcommand_search_strings(
string = "./cmd"
# Text of cmd tag in query was added as attribute to response
if app_command_cmd.cmd_text:
string = string + "[@{}='{}']".format(
APPCOMMAND_CMD_TEXT, app_command_cmd.cmd_text
string = (
string + f"[@{APPCOMMAND_CMD_TEXT}='{app_command_cmd.cmd_text}']"
)
# Text of name tag in query was added as attribute to response
if app_command_cmd.name:
string = string + "[@{}='{}']".format(
APPCOMMAND_NAME, app_command_cmd.name
)
string = string + f"[@{APPCOMMAND_NAME}='{app_command_cmd.name}']"
# Some results include a zone tag
if resp.add_zone:
string = string + "/{}".format(zone)
string = string + f"/{zone}"
# Suffix like /status, /volume
string = string + resp.suffix

Expand Down
Loading

0 comments on commit 208fd3c

Please sign in to comment.