diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py index 378f12167c6842..3b21658433b2ed 100644 --- a/Lib/ctypes/util.py +++ b/Lib/ctypes/util.py @@ -85,15 +85,10 @@ def find_library(name): 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 @@ def _get_module_filename(module: wintypes.HMODULE): 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 index 00000000000000..6f039197962e10 --- /dev/null +++ b/Misc/NEWS.d/next/Windows/2026-02-27-10-57-20.gh-issue-145307.ueoT7j.rst @@ -0,0 +1,2 @@ +Defers loading of the ``psapi.dll`` module until it is used by +:func:`ctypes.util.dllist`.