]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-145307: Defer loading psapi.dll until ctypes.util.dllist() is called. (GH-145308)
authorSteve Dower <steve.dower@python.org>
Mon, 2 Mar 2026 16:10:15 +0000 (16:10 +0000)
committerGitHub <noreply@github.com>
Mon, 2 Mar 2026 16:10:15 +0000 (17:10 +0100)
Lib/ctypes/util.py
Misc/NEWS.d/next/Windows/2026-02-27-10-57-20.gh-issue-145307.ueoT7j.rst [new file with mode: 0644]

index 378f12167c6842ace7709c4da8f9126aaf8b6bd3..3b21658433b2edb78336e7479ddce704db630718 100644 (file)
@@ -85,15 +85,10 @@ if os.name == "nt":
         wintypes.DWORD,
     )
 
-    _psapi = ctypes.WinDLL('psapi', use_last_error=True)
-    _enum_process_modules = _psapi["EnumProcessModules"]
-    _enum_process_modules.restype = wintypes.BOOL
-    _enum_process_modules.argtypes = (
-        wintypes.HANDLE,
-        ctypes.POINTER(wintypes.HMODULE),
-        wintypes.DWORD,
-        wintypes.LPDWORD,
-    )
+    # gh-145307: We defer loading psapi.dll until _get_module_handles is called.
+    # Loading additional DLLs at startup for functionality that may never be
+    # used is wasteful.
+    _enum_process_modules = None
 
     def _get_module_filename(module: wintypes.HMODULE):
         name = (wintypes.WCHAR * 32767)() # UNICODE_STRING_MAX_CHARS
@@ -101,8 +96,19 @@ if os.name == "nt":
             return name.value
         return None
 
-
     def _get_module_handles():
+        global _enum_process_modules
+        if _enum_process_modules is None:
+            _psapi = ctypes.WinDLL('psapi', use_last_error=True)
+            _enum_process_modules = _psapi["EnumProcessModules"]
+            _enum_process_modules.restype = wintypes.BOOL
+            _enum_process_modules.argtypes = (
+                wintypes.HANDLE,
+                ctypes.POINTER(wintypes.HMODULE),
+                wintypes.DWORD,
+                wintypes.LPDWORD,
+            )
+
         process = _get_current_process()
         space_needed = wintypes.DWORD()
         n = 1024
diff --git a/Misc/NEWS.d/next/Windows/2026-02-27-10-57-20.gh-issue-145307.ueoT7j.rst b/Misc/NEWS.d/next/Windows/2026-02-27-10-57-20.gh-issue-145307.ueoT7j.rst
new file mode 100644 (file)
index 0000000..6f03919
--- /dev/null
@@ -0,0 +1,2 @@
+Defers loading of the ``psapi.dll`` module until it is used by
+:func:`ctypes.util.dllist`.