Skip to content

Commit

Permalink
core: services: helper: make scan_ports pythonic
Browse files Browse the repository at this point in the history
- `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)
  • Loading branch information
ES-Alexander authored and patrickelectric committed Oct 28, 2021
1 parent 9648e3e commit 72256d5
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions core/services/helper/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 72256d5

Please sign in to comment.