From c1cc90e81c7be7033d9acb03b06fa03f1bc9116b Mon Sep 17 00:00:00 2001 From: Alex Ruddick Date: Sun, 9 Apr 2023 22:14:29 -0500 Subject: [PATCH 1/7] SIM105: use contextlib.suppress() --- examples/contrib/redis_datastore.py | 5 ++--- pymodbus/client/serial.py | 5 ++--- pymodbus/server/async_io.py | 9 +++------ pymodbus/transaction.py | 8 ++++---- ruff.toml | 1 + test/test_repl_client.py | 14 +++++--------- test/test_server_asyncio.py | 9 +++------ 7 files changed, 20 insertions(+), 31 deletions(-) diff --git a/examples/contrib/redis_datastore.py b/examples/contrib/redis_datastore.py index 73801212a..14d96d633 100644 --- a/examples/contrib/redis_datastore.py +++ b/examples/contrib/redis_datastore.py @@ -1,11 +1,10 @@ """Datastore using redis.""" # pylint: disable=missing-type-doc +from contextlib import suppress -try: +with suppress(ImportError): import redis -except ImportError: - pass from pymodbus.datastore import ModbusBaseSlaveContext from pymodbus.logging import Log diff --git a/pymodbus/client/serial.py b/pymodbus/client/serial.py index e53b88f75..1f6f1d6e9 100644 --- a/pymodbus/client/serial.py +++ b/pymodbus/client/serial.py @@ -1,6 +1,7 @@ """Modbus client async serial communication.""" import asyncio import time +from contextlib import suppress from functools import partial from typing import Any, Type @@ -14,10 +15,8 @@ from pymodbus.utilities import ModbusTransactionState -try: +with suppress(ImportError): import serial -except ImportError: - pass class AsyncModbusSerialClient(ModbusBaseClient, asyncio.Protocol): diff --git a/pymodbus/server/async_io.py b/pymodbus/server/async_io.py index 384c0f3b1..20665f6c1 100644 --- a/pymodbus/server/async_io.py +++ b/pymodbus/server/async_io.py @@ -4,6 +4,7 @@ import ssl import time import traceback +from contextlib import suppress from typing import Union from pymodbus.client.serial_asyncio import create_serial_connection @@ -22,10 +23,8 @@ ) -try: +with suppress(ImportError): import serial -except ImportError: - pass def sslctx_provider( @@ -1072,10 +1071,8 @@ async def run(cls, server, custom_functions): for func in custom_functions: server.decoder.register(func) cls.active_server = _serverList(server) - try: + with suppress(asyncio.exceptions.CancelledError): await server.serve_forever() - except asyncio.CancelledError: - pass @classmethod async def async_stop(cls): diff --git a/pymodbus/transaction.py b/pymodbus/transaction.py index 230008b39..e3a56200a 100644 --- a/pymodbus/transaction.py +++ b/pymodbus/transaction.py @@ -13,6 +13,7 @@ # pylint: disable=missing-type-doc import struct import time +from contextlib import suppress from functools import partial from threading import RLock @@ -374,15 +375,14 @@ def _recv(self, expected_response_length, full): # pylint: disable=too-complex elif expected_response_length is None and isinstance( self.client.framer, ModbusRtuFramer ): - try: + with suppress( + IndexError # response length indeterminate with available bytes + ): expected_response_length = ( self.client.framer.get_expected_response_length( read_min ) ) - except IndexError: - # Could not determine response length with available bytes - pass if expected_response_length is not None: expected_response_length -= min_size total = expected_response_length + min_size diff --git a/ruff.toml b/ruff.toml index 7aa5d1c7b..519e996aa 100644 --- a/ruff.toml +++ b/ruff.toml @@ -18,6 +18,7 @@ select = [ "E", "F", "W", + "SIM105", ] [pydocstyle] convention = "pep257" diff --git a/test/test_repl_client.py b/test/test_repl_client.py index 6a51acd48..5f39650f1 100755 --- a/test/test_repl_client.py +++ b/test/test_repl_client.py @@ -1,4 +1,6 @@ """Test client sync.""" +from contextlib import suppress + from pymodbus.repl.client.main import _process_args from pymodbus.server.reactive.default_config import DEFAULT_CONFIG @@ -32,17 +34,11 @@ def test_repl_client_process_args(): resp = _process_args(["address=0b11", "value=0x10"], False) assert resp == ({"address": 3, "value": 16}, True) - try: + with suppress(ValueError): resp = _process_args(["address=0xhj", "value=0x10"], False) - except ValueError: - pass - try: + with suppress(ValueError): resp = _process_args(["address=11ah", "value=0x10"], False) - except ValueError: - pass - try: + with suppress(ValueError): resp = _process_args(["address=0b12", "value=0x10"], False) - except ValueError: - pass diff --git a/test/test_server_asyncio.py b/test/test_server_asyncio.py index 518e008e4..23fbdbd37 100755 --- a/test/test_server_asyncio.py +++ b/test/test_server_asyncio.py @@ -3,6 +3,7 @@ import logging import ssl from asyncio import CancelledError +from contextlib import suppress from unittest import mock import pytest @@ -127,19 +128,15 @@ async def setup_teardown(self): await asyncio.sleep(0.1) if not self.task.cancelled(): self.task.cancel() - try: + with suppress(CancelledError): await self.task - except CancelledError: - pass self.task = None BasicClient.clear() def handle_task(self, result): """Handle task exit.""" - try: + with suppress(CancelledError): result = result.result() - except CancelledError: - pass async def start_server( self, do_forever=True, do_defer=True, do_tls=False, do_udp=False, do_ident=False From 43eebc8bf976963090b326dcaa0f1c9bcdda5bd4 Mon Sep 17 00:00:00 2001 From: Alex Ruddick Date: Sun, 9 Apr 2023 22:15:46 -0500 Subject: [PATCH 2/7] SIM117: Use multiple contexts in with --- ruff.toml | 1 + test/test_server_asyncio.py | 9 ++++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ruff.toml b/ruff.toml index 519e996aa..cdf3f532a 100644 --- a/ruff.toml +++ b/ruff.toml @@ -19,6 +19,7 @@ select = [ "F", "W", "SIM105", + "SIM117", ] [pydocstyle] convention = "pep257" diff --git a/test/test_server_asyncio.py b/test/test_server_asyncio.py index 23fbdbd37..f8f6bd640 100755 --- a/test/test_server_asyncio.py +++ b/test/test_server_asyncio.py @@ -294,11 +294,10 @@ async def test_async_tls_server_serve_forever(self): """Test StartAsyncTcpServer serve_forever() method""" with mock.patch( "asyncio.base_events.Server.serve_forever", new_callable=mock.AsyncMock - ) as serve: - with mock.patch.object(ssl.SSLContext, "load_cert_chain"): - await self.start_server(do_tls=True, do_forever=False) - await self.server.serve_forever() - serve.assert_awaited() + ) as serve, mock.patch.object(ssl.SSLContext, "load_cert_chain"): + await self.start_server(do_tls=True, do_forever=False) + await self.server.serve_forever() + serve.assert_awaited() async def test_async_tls_server_serve_forever_twice(self): """Call on serve_forever() twice should result in a runtime error""" From 9a8daf5c53a373eae579ad855dff5692d9c9c48d Mon Sep 17 00:00:00 2001 From: Alex Ruddick Date: Sun, 9 Apr 2023 22:18:19 -0500 Subject: [PATCH 3/7] SIM201: {a} != {b} instead of not {a} == {b} --- pymodbus/server/simulator/http_server.py | 2 +- ruff.toml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pymodbus/server/simulator/http_server.py b/pymodbus/server/simulator/http_server.py index 2fd767c4d..02e3c4ea9 100644 --- a/pymodbus/server/simulator/http_server.py +++ b/pymodbus/server/simulator/http_server.py @@ -598,7 +598,7 @@ def server_response_manipulator(self, response): self.call_list.append(tracer) self.call_monitor.trace_response = False - if not self.call_response.active == RESPONSE_INACTIVE: + if self.call_response.active != RESPONSE_INACTIVE: return response, False skip_encoding = False diff --git a/ruff.toml b/ruff.toml index cdf3f532a..517601af6 100644 --- a/ruff.toml +++ b/ruff.toml @@ -20,6 +20,7 @@ select = [ "W", "SIM105", "SIM117", + "SIM201", ] [pydocstyle] convention = "pep257" From 0acac00ab4b76da976ee2dcfdf5e03024a6fbdbf Mon Sep 17 00:00:00 2001 From: Alex Ruddick Date: Sun, 9 Apr 2023 22:19:26 -0500 Subject: [PATCH 4/7] SIM300: Yoda conditions --- ruff.toml | 1 + test/test_client.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ruff.toml b/ruff.toml index 517601af6..07b8ea04d 100644 --- a/ruff.toml +++ b/ruff.toml @@ -21,6 +21,7 @@ select = [ "SIM105", "SIM117", "SIM201", + "SIM300", ] [pydocstyle] convention = "pep257" diff --git a/test/test_client.py b/test/test_client.py index 451455cd2..d5376ed66 100755 --- a/test/test_client.py +++ b/test/test_client.py @@ -258,9 +258,9 @@ async def test_client_instanciate( assert client.delay_ms == initial_delay rc1 = client._get_address_family("127.0.0.1") # pylint: disable=protected-access - assert socket.AF_INET == rc1 + assert rc1 == socket.AF_INET rc2 = client._get_address_family("::1") # pylint: disable=protected-access - assert socket.AF_INET6 == rc2 + assert rc2 == socket.AF_INET6 # a successful execute client.connect = lambda: True From 5f5471dcebd920c885351fc9ec3b9651746e3b99 Mon Sep 17 00:00:00 2001 From: Alex Ruddick Date: Sun, 9 Apr 2023 22:22:07 -0500 Subject: [PATCH 5/7] Remaining pyflakes-simplify rules used by HomeAssistant --- ruff.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ruff.toml b/ruff.toml index 07b8ea04d..7903d05ae 100644 --- a/ruff.toml +++ b/ruff.toml @@ -20,8 +20,11 @@ select = [ "W", "SIM105", "SIM117", + "SIM118", "SIM201", + "SIM212", "SIM300", + "SIM401", ] [pydocstyle] convention = "pep257" From a9a9a2c8df67938173d2b3d9953bd16f67bd7edb Mon Sep 17 00:00:00 2001 From: Alex Ruddick Date: Sun, 9 Apr 2023 22:42:30 -0500 Subject: [PATCH 6/7] docstring --- examples/server_updating.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/examples/server_updating.py b/examples/server_updating.py index cf7de50d3..3785d521f 100755 --- a/examples/server_updating.py +++ b/examples/server_updating.py @@ -42,10 +42,9 @@ async def updating_task(context): - """Run every so often, + """Run every so often and update live values of the context. - and updates live values of the context. It should be noted - that there is a lrace condition for the update. + It should be noted that there is a race condition for the update. """ _logger.debug("updating the context") fc_as_hex = 3 From da17854dd34914a1c1af2eddfcd8b994c8e35ed7 Mon Sep 17 00:00:00 2001 From: Alex Ruddick Date: Sun, 9 Apr 2023 22:42:42 -0500 Subject: [PATCH 7/7] Enable "RUF" rules --- examples/server_updating.py | 2 +- ruff.toml | 1 + test/test_unix_socket.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/server_updating.py b/examples/server_updating.py index 3785d521f..dc45b3d8e 100755 --- a/examples/server_updating.py +++ b/examples/server_updating.py @@ -76,7 +76,7 @@ def setup_updating_server(cmdline=None): async def run_updating_server(args): """Start updater task and async server.""" - asyncio.create_task(updating_task(args.context)) + asyncio.create_task(updating_task(args.context)) # noqa: RUF006 await run_async_server(args) diff --git a/ruff.toml b/ruff.toml index 7903d05ae..c3afe50b4 100644 --- a/ruff.toml +++ b/ruff.toml @@ -25,6 +25,7 @@ select = [ "SIM212", "SIM300", "SIM401", + "RUF", ] [pydocstyle] convention = "pep257" diff --git a/test/test_unix_socket.py b/test/test_unix_socket.py index 57c2125bf..d41c1ab04 100755 --- a/test/test_unix_socket.py +++ b/test/test_unix_socket.py @@ -31,7 +31,7 @@ async def _helper_server(path_addon): context = ModbusSlaveContext( di=datablock, co=datablock, hr=datablock, ir=datablock, slave=1 ) - asyncio.create_task( + asyncio.create_task( # noqa: RUF006 StartAsyncUnixServer( context=ModbusServerContext(slaves=context, single=True), path=PATH + path_addon,