From 72256d5cbe2ddc9b50405356338dbe19a69ed203 Mon Sep 17 00:00:00 2001 From: ES-Alexander Date: Thu, 28 Oct 2021 19:44:42 +1100 Subject: [PATCH] core: services: helper: make `scan_ports` pythonic - `list`s are already iterable, so no need to create an iterator (`iter`) to iterate over them - use generator expressions for efficient single-iteration filtering (`filter`ing with `lambda`s generally isn't great because it unnecessarily constructs and applies functions just to perform simple comparisons) - keep the return value as a list, to avoid overburdening the user/receiver (they may wish to iterate more than once, or could require random access) --- core/services/helper/main.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/core/services/helper/main.py b/core/services/helper/main.py index 3f966c1f09..aab86f8c5b 100755 --- a/core/services/helper/main.py +++ b/core/services/helper/main.py @@ -63,16 +63,16 @@ def detect_service(port: int) -> ServiceInfo: @temporary_cache(timeout_seconds=10) def scan_ports() -> List[ServiceInfo]: # Filter for TCP ports that are listen and can be accessed by external users (server in 0.0.0.0) - connections = iter(psutil.net_connections("tcp")) - connections = filter(lambda connection: connection.status == psutil.CONN_LISTEN, connections) - connections = filter(lambda connection: connection.laddr.ip in Helper.LOCALSERVER_CANDIDATES, connections) + connections = ( + connection + for connection in psutil.net_connections("tcp") + if connection.status == psutil.CONN_LISTEN and connection.laddr.ip in Helper.LOCALSERVER_CANDIDATES + ) # And check if there is a webpage available that is not us - ports = iter([connection.laddr.port for connection in connections]) - ports = filter(lambda port: port != PORT, ports) - services = map(Helper.detect_service, ports) - valid_services = filter(lambda service: service.valid, services) - return list(valid_services) + ports = (connection.laddr.port for connection in connections) + services = (Helper.detect_service(port) for port in ports if port != PORT) + return [service for service in services if service.valid] fast_api_app = FastAPI(