From 1e9320ce5fa90777e5d5fb680c79b886be895703 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B5=D0=BD=D0=B8=D1=81=20=D0=9F=D0=B5=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B2?= Date: Wed, 1 May 2024 20:46:31 +0600 Subject: [PATCH] add refactoring to fix linter errors --- snap7/util.py | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/snap7/util.py b/snap7/util.py index cfa8082d..e7fd0748 100644 --- a/snap7/util.py +++ b/snap7/util.py @@ -556,8 +556,10 @@ def get_string(bytearray_: bytearray, byte_index: int) -> str: if str_length > max_string_size or max_string_size > 254: logger.error("The string is too big for the size encountered in specification") logger.error("WRONG SIZED STRING ENCOUNTERED") - raise TypeError("String contains {} chars, but max. {} chars are expected or is larger than 254." - "Bytearray doesn't seem to be a valid string.".format(str_length, max_string_size)) + raise TypeError( + f"String contains {str_length} chars, but max. {max_string_size} chars are expected or is larger than 254." + "Bytearray doesn't seem to be a valid string." + ) data = map(chr, bytearray_[byte_index + 2:byte_index + 2 + str_length]) return "".join(data) @@ -1783,19 +1785,11 @@ def set_value(self, byte_index: Union[str, int], type_: str, value: Union[bool, byte_index = self.get_offset(byte_index) if type_.startswith('FSTRING') and isinstance(value, str): - max_size = re.search(r'\d+', type_) - if max_size is None: - raise ValueError("Max size could not be determinate. re.search() returned None") - max_size_grouped = max_size.group(0) - max_size_int = int(max_size_grouped) + max_size_int = self._get_max_size(type_) return set_fstring(bytearray_, byte_index, value, max_size_int) if type_.startswith('STRING') and isinstance(value, str): - max_size = re.search(r'\d+', type_) - if max_size is None: - raise ValueError("Max size could not be determinate. re.search() returned None") - max_size_grouped = max_size.group(0) - max_size_int = int(max_size_grouped) + max_size_int = self._get_max_size(type_) return set_string(bytearray_, byte_index, value, max_size_int) if type_ == 'REAL': @@ -1878,3 +1872,12 @@ def read(self, client: Client) -> None: # replace data in bytearray for i, b in enumerate(bytearray_): data[i + self.db_offset] = b + + def _get_max_size(self, type_: str) -> int: + max_size = re.search(r"\d+", type_) + if max_size is None: + raise ValueError( + "Max size could not be determinate. re.search() returned None" + ) + max_size_grouped = max_size.group(0) + return int(max_size_grouped)