From ef7597dac8e5c53ff51a6c8fd7f7cde4221ce79e Mon Sep 17 00:00:00 2001 From: mikemikimike <13286568797@163.com> Date: Sat, 29 Aug 2026 20:47:33 +0800 Subject: [PATCH] Allow Trio imports on Android without interface helpers --- newsfragments/3493.bugfix.rst | 1 + src/trio/_tests/test_socket.py | 28 ++++++++++++++++++++++++++++ src/trio/socket.py | 10 ++++++---- 3 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 newsfragments/3493.bugfix.rst diff --git a/newsfragments/3493.bugfix.rst b/newsfragments/3493.bugfix.rst new file mode 100644 index 0000000000..339c3f566a --- /dev/null +++ b/newsfragments/3493.bugfix.rst @@ -0,0 +1 @@ +Allow importing Trio on Android API levels where ``socket.if_indextoname`` and ``socket.if_nametoindex`` are unavailable. diff --git a/src/trio/_tests/test_socket.py b/src/trio/_tests/test_socket.py index 03918b0e1f..d6a56863d3 100644 --- a/src/trio/_tests/test_socket.py +++ b/src/trio/_tests/test_socket.py @@ -4,6 +4,7 @@ import inspect import os import socket as stdlib_socket +import subprocess import sys import tempfile from pathlib import Path @@ -167,6 +168,33 @@ def test_socket_has_some_reexports() -> None: assert tsocket.ntohs == stdlib_socket.ntohs +def test_imports_without_android_interface_helpers() -> None: + script = """ +import socket as real_socket +import sys +import types + +fake_socket = types.ModuleType("socket") +fake_socket.__dict__.update(real_socket.__dict__) +del fake_socket.if_indextoname +del fake_socket.if_nametoindex +sys.modules["socket"] = fake_socket + +import trio.socket +""" + environment = os.environ.copy() + source_path = str(Path(__file__).parents[2]) + environment["PYTHONPATH"] = os.pathsep.join( + [source_path, environment.get("PYTHONPATH", "")] + ) + subprocess.run( + [sys.executable, "-c", script], + cwd=Path(__file__).parents[3], + env=environment, + check=True, + ) + + ################################################################ # name resolution ################################################################ diff --git a/src/trio/socket.py b/src/trio/socket.py index 4aee184331..2ce4cd75b0 100644 --- a/src/trio/socket.py +++ b/src/trio/socket.py @@ -69,10 +69,12 @@ ) if sys.implementation.name == "cpython": - from socket import ( - if_indextoname as if_indextoname, - if_nametoindex as if_nametoindex, - ) + # These functions are not available on all Android API levels. + with _suppress(ImportError): + from socket import ( + if_indextoname as if_indextoname, + if_nametoindex as if_nametoindex, + ) # For android devices, if_nameindex support was introduced in API 24, # so it doesn't exist for any version prior.