From 368590cd36145b0b7786bb248ae7cbfcce30180c Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 30 Jun 2024 04:49:59 -0500 Subject: [PATCH] Cache SmartErrorCode creation (#1022) Uses the python 3.9 cache feature to improve performance of error code creation --- kasa/aestransport.py | 5 ++--- kasa/exceptions.py | 7 +++++++ kasa/smartprotocol.py | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/kasa/aestransport.py b/kasa/aestransport.py index 72df4e17..cc373b19 100644 --- a/kasa/aestransport.py +++ b/kasa/aestransport.py @@ -142,12 +142,11 @@ class AesTransport(BaseTransport): def _handle_response_error_code(self, resp_dict: Any, msg: str) -> None: error_code_raw = resp_dict.get("error_code") try: - error_code = SmartErrorCode(error_code_raw) # type: ignore[arg-type] + error_code = SmartErrorCode.from_int(error_code_raw) except ValueError: _LOGGER.warning("Received unknown error code: %s", error_code_raw) error_code = SmartErrorCode.INTERNAL_UNKNOWN_ERROR - - if error_code == SmartErrorCode.SUCCESS: + if error_code is SmartErrorCode.SUCCESS: return msg = f"{msg}: {self._host}: {error_code.name}({error_code.value})" if error_code in SMART_RETRYABLE_ERRORS: diff --git a/kasa/exceptions.py b/kasa/exceptions.py index 2d913c2a..f5c26ff0 100644 --- a/kasa/exceptions.py +++ b/kasa/exceptions.py @@ -4,6 +4,7 @@ from __future__ import annotations from asyncio import TimeoutError as _asyncioTimeoutError from enum import IntEnum +from functools import cache from typing import Any @@ -63,6 +64,12 @@ class SmartErrorCode(IntEnum): def __str__(self): return f"{self.name}({self.value})" + @staticmethod + @cache + def from_int(value: int) -> SmartErrorCode: + """Convert an integer to a SmartErrorCode.""" + return SmartErrorCode(value) + SUCCESS = 0 # Transport Errors diff --git a/kasa/smartprotocol.py b/kasa/smartprotocol.py index a430e3af..22fd49dc 100644 --- a/kasa/smartprotocol.py +++ b/kasa/smartprotocol.py @@ -241,12 +241,12 @@ class SmartProtocol(BaseProtocol): def _handle_response_error_code(self, resp_dict: dict, method, raise_on_error=True): error_code_raw = resp_dict.get("error_code") try: - error_code = SmartErrorCode(error_code_raw) # type: ignore[arg-type] + error_code = SmartErrorCode.from_int(error_code_raw) except ValueError: _LOGGER.warning("Received unknown error code: %s", error_code_raw) error_code = SmartErrorCode.INTERNAL_UNKNOWN_ERROR - if error_code == SmartErrorCode.SUCCESS: + if error_code is SmartErrorCode.SUCCESS: return if not raise_on_error: