diff --git a/Lib/platform.py b/Lib/platform.py index c87bf2fca37e031..2e7b74ab48544ee 100644 --- a/Lib/platform.py +++ b/Lib/platform.py @@ -114,10 +114,7 @@ import functools import itertools lazy import warnings -try: - import _wmi -except ImportError: - _wmi = None +lazy import _wmi ### Globals & Constants @@ -331,8 +328,9 @@ def _syscmd_ver(system='', release='', version='', def _wmi_query(table, *keys): - global _wmi - if not _wmi: + try: + _wmi # Force the deferred import. + except ImportError: raise OSError("not supported") table = { "OS": "Win32_OperatingSystem", @@ -344,7 +342,6 @@ def _wmi_query(table, *keys): table, )).split("\0") except OSError: - _wmi = None raise OSError("not supported") split_data = (i.partition("=") for i in data) dict_data = {i[0]: i[2] for i in split_data} diff --git a/Lib/test/test_platform.py b/Lib/test/test_platform.py index cf3ca9021eea3fb..77d6b3bce4f66b6 100644 --- a/Lib/test/test_platform.py +++ b/Lib/test/test_platform.py @@ -11,7 +11,7 @@ from unittest import mock from test import support -from test.support import os_helper, warnings_helper +from test.support import import_helper, os_helper, warnings_helper try: # Some of the iOS tests need ctypes to operate. @@ -436,6 +436,10 @@ def test_win32_ver_on_non_windows(self): res = platform.win32_ver(release, version, csd, ptype) self.assertSequenceEqual(res, (release, version, csd, ptype), seq_type=tuple) + @support.cpython_only + def test_wmi_is_lazily_imported(self): + import_helper.ensure_lazy_imports('platform', {'_wmi'}) + def test_mac_ver(self): res = platform.mac_ver() diff --git a/Misc/NEWS.d/next/Library/2026-11-07-08-37-10.gh-issue-161513.72f4f1.rst b/Misc/NEWS.d/next/Library/2026-11-07-08-37-10.gh-issue-161513.72f4f1.rst new file mode 100644 index 000000000000000..8e2360be613141a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-07-08-37-10.gh-issue-161513.72f4f1.rst @@ -0,0 +1 @@ +:mod:`platform` is now about 30% faster to import on Windows.