Skip to content

Commit 7848a9f

Browse files
cmaloneyclaude
andcommitted
gh-71199: Use os rather than posix or nt in the stdlib
shutil, pathlib, _pyrepl, _colorize and ctypes imported or guarded the platform module for its private helpers; use them from os instead. select imports _os. ntpath and posixpath import their fast paths from _os; both are importable on every platform, so they still check it first. Tests follow: those that skipped without posix or nt now run everywhere when they only needed _os (the ismount mocks), or check for the Windows-only helper they exercise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 616afa3 commit 7848a9f

20 files changed

Lines changed: 98 additions & 139 deletions

‎Doc/using/configure.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1787,7 +1787,7 @@ Compiler flags
17871787
.. envvar:: PY_BUILTIN_MODULE_CFLAGS
17881788

17891789
Compiler flags to build a standard library extension module as a built-in
1790-
module, like the :mod:`posix` module.
1790+
module, like the ``_os`` module.
17911791

17921792
Default: ``$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE_BUILTIN``.
17931793

‎Lib/_colorize.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -593,11 +593,9 @@ def _safe_getenv(k: str, fallback: str | None = None) -> str | None:
593593

594594
if sys.platform == "win32":
595595
try:
596-
import nt
597-
598-
if not nt._supports_virtual_terminal():
596+
if not os._supports_virtual_terminal():
599597
return False
600-
except (ImportError, AttributeError):
598+
except AttributeError:
601599
return False
602600

603601
try:

‎Lib/_pyrepl/trace.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212

1313
if sys.platform == "emscripten":
14-
from posix import _emscripten_log
14+
_emscripten_log = os._emscripten_log
1515

1616
def trace(line: str, *k: object, **kw: object) -> None:
1717
if "PYREPL_TRACE" not in os.environ:

‎Lib/_pyrepl/unix_console.py‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
import struct
2828
import termios
2929
import time
30-
import types
3130
import platform
3231
from collections.abc import Callable
3332
from dataclasses import dataclass
@@ -51,13 +50,6 @@
5150
from .trace import trace, trace_text
5251
from .unix_eventqueue import EventQueue
5352

54-
# declare posix optional to allow None assignment on other platforms
55-
posix: types.ModuleType | None
56-
try:
57-
import posix
58-
except ImportError:
59-
posix = None
60-
6153
# types
6254
type _MoveFunc = Callable[[int, int], None]
6355
type _PendingWrite = tuple[str | bytes, bool]
@@ -726,7 +718,7 @@ def clear(self):
726718
def input_hook(self):
727719
# avoid inline imports here so the repl doesn't get flooded
728720
# with import logging from -X importtime=2
729-
if posix is not None and posix._is_inputhook_installed():
721+
if os._is_inputhook_installed():
730722
return self.__run_input_hook
731723

732724
def __run_input_hook(self):
@@ -737,7 +729,7 @@ def __run_input_hook(self):
737729
cooked.oflag = self.__svtermstate.oflag
738730
self.__input_fd_set(cooked)
739731
try:
740-
return posix._inputhook()
732+
return os._inputhook()
741733
finally:
742734
self.__input_fd_set(self.__rawtermstate)
743735

‎Lib/_pyrepl/windows_console.py‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,10 @@ def __init__(self, err: int | None, descr: str | None = None) -> None:
6868

6969
# declare optional to allow None assignment on other platforms
7070
_winapi: types.ModuleType | None
71-
nt: types.ModuleType | None
7271
try:
7372
import _winapi
74-
import nt
7573
except ImportError:
7674
_winapi = None
77-
nt = None
7875

7976
lazy from typing import IO
8077

@@ -145,7 +142,7 @@ class WindowsRefreshPlan:
145142

146143
def _supports_vt():
147144
try:
148-
return nt._supports_virtual_terminal()
145+
return os._supports_virtual_terminal()
149146
except AttributeError:
150147
return False
151148

@@ -312,8 +309,8 @@ def __apply_refresh_plan(self, plan: WindowsRefreshPlan) -> None:
312309
def input_hook(self):
313310
# avoid inline imports here so the repl doesn't get flooded
314311
# with import logging from -X importtime=2
315-
if nt is not None and nt._is_inputhook_installed():
316-
return nt._inputhook
312+
if os._is_inputhook_installed():
313+
return os._inputhook
317314

318315
def __plan_changed_line( # keep in sync with UnixConsole.__plan_changed_line
319316
self,

‎Lib/ctypes/__init__.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -430,16 +430,15 @@ class _FuncPtr(_CFuncPtr):
430430
if _os.name == "nt":
431431
def _load_library(self, name, mode, handle, winmode):
432432
if winmode is None:
433-
import nt as _nt
434-
winmode = _nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
433+
winmode = _os._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
435434
# WINAPI LoadLibrary searches for a DLL if the given name
436435
# is not fully qualified with an explicit drive. For POSIX
437436
# compatibility, and because the DLL search path no longer
438437
# contains the working directory, begin by fully resolving
439438
# any name that contains a path separator.
440439
if name is not None and ('/' in name or '\\' in name):
441-
name = _nt._getfullpathname(name)
442-
winmode |= _nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
440+
name = _os._getfullpathname(name)
441+
winmode |= _os._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
443442
self._name = name
444443
if handle is not None:
445444
return handle

‎Lib/ntpath.py‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -168,9 +168,10 @@ def splitdrive(p, /):
168168
return drive, root + tail
169169

170170

171-
try:
172-
from nt import _path_splitroot_ex as splitroot
173-
except ImportError:
171+
# Elsewhere, _os has the POSIX versions of these.
172+
if sys.platform == 'win32':
173+
from _os import _path_splitroot_ex as splitroot
174+
else:
174175
def splitroot(p, /):
175176
"""Split a pathname into drive, root and tail.
176177
@@ -276,7 +277,7 @@ def dirname(p, /):
276277
# common case: drive letter roots. The alternative which uses GetVolumePathName
277278
# fails if the drive letter is the result of a SUBST.
278279
try:
279-
from nt import _getvolumepathname
280+
from _os import _getvolumepathname
280281
except ImportError:
281282
_getvolumepathname = None
282283
def ismount(path):
@@ -470,10 +471,10 @@ def repl(m):
470471
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
471472
# Previously, this function also truncated pathnames to 8+3 format,
472473
# but as this module is called "ntpath", that's obviously wrong!
473-
try:
474-
from nt import _path_normpath as normpath
474+
if sys.platform == 'win32':
475+
from _os import _path_normpath as normpath
475476

476-
except ImportError:
477+
else:
477478
def normpath(path):
478479
"""Normalize path, eliminating double slashes, etc."""
479480
path = os.fspath(path)
@@ -513,7 +514,7 @@ def normpath(path):
513514

514515
# Return an absolute path.
515516
try:
516-
from nt import _getfullpathname
517+
from _os import _getfullpathname
517518

518519
except ImportError: # not running on Windows - mock up something sensible
519520
def abspath(path):
@@ -556,7 +557,7 @@ def abspath(path):
556557
return normpath(path)
557558

558559
try:
559-
from nt import _findfirstfile, _getfinalpathname, readlink as _nt_readlink
560+
from _os import _findfirstfile, _getfinalpathname, readlink as _nt_readlink
560561
except ImportError:
561562
# realpath is a no-op on systems without _getfinalpathname support.
562563
def realpath(path, /, *, strict=False):
@@ -881,19 +882,19 @@ def commonpath(paths):
881882
# The isdir(), isfile(), islink(), exists() and lexists() implementations
882883
# in genericpath use os.stat(). This is overkill on Windows. Use simpler
883884
# builtin functions if they are available.
884-
from nt import _path_isdir as isdir
885-
from nt import _path_isfile as isfile
886-
from nt import _path_islink as islink
887-
from nt import _path_isjunction as isjunction
888-
from nt import _path_exists as exists
889-
from nt import _path_lexists as lexists
885+
from _os import _path_isdir as isdir
886+
from _os import _path_isfile as isfile
887+
from _os import _path_islink as islink
888+
from _os import _path_isjunction as isjunction
889+
from _os import _path_exists as exists
890+
from _os import _path_lexists as lexists
890891
except ImportError:
891892
# Use genericpath.* as imported above
892893
pass
893894

894895

895896
try:
896-
from nt import _path_isdevdrive
897+
from _os import _path_isdevdrive
897898
def isdevdrive(path):
898899
"""Determines whether the specified path is on a Windows Dev Drive."""
899900
try:

‎Lib/pathlib/_os.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,6 @@
1010
import fcntl
1111
except ImportError:
1212
fcntl = None
13-
try:
14-
import posix
15-
except ImportError:
16-
posix = None
1713
try:
1814
import _winapi
1915
except ImportError:
@@ -51,13 +47,13 @@ def _ficlone(source_fd, target_fd):
5147
_ficlone = None
5248

5349

54-
if posix and hasattr(posix, '_fcopyfile'):
50+
if hasattr(os, '_fcopyfile'):
5551
def _fcopyfile(source_fd, target_fd):
5652
"""
5753
Copy a regular file content using high-performance fcopyfile(3)
5854
syscall (macOS).
5955
"""
60-
posix._fcopyfile(source_fd, target_fd, posix._COPYFILE_DATA)
56+
os._fcopyfile(source_fd, target_fd, os._COPYFILE_DATA)
6157
else:
6258
_fcopyfile = None
6359

‎Lib/posixpath.py‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,10 @@ def splitdrive(p, /):
136136
return p[:0], p
137137

138138

139-
try:
140-
from posix import _path_splitroot_ex as splitroot
141-
except ImportError:
139+
# On Windows, _os has the Windows versions of these.
140+
if sys.platform != 'win32':
141+
from _os import _path_splitroot_ex as splitroot
142+
else:
142143
def splitroot(p, /):
143144
"""Split a pathname into drive, root and tail.
144145
@@ -338,10 +339,10 @@ def repl(m):
338339
# It should be understood that this may change the meaning of the path
339340
# if it contains symbolic links!
340341

341-
try:
342-
from posix import _path_normpath as normpath
342+
if sys.platform != 'win32':
343+
from _os import _path_normpath as normpath
343344

344-
except ImportError:
345+
else:
345346
def normpath(path):
346347
"""Normalize path, eliminating double slashes, etc."""
347348
path = os.fspath(path)

‎Lib/shutil.py‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,6 @@
4545
_ZSTD_SUPPORTED = False
4646

4747
_WINDOWS = os.name == 'nt'
48-
posix = nt = None
49-
if os.name == 'posix':
50-
import posix
51-
elif _WINDOWS:
52-
import nt
5348

5449
if sys.platform == 'win32':
5550
import _winapi
@@ -62,7 +57,7 @@
6257
_USE_CP_SENDFILE = (hasattr(os, "sendfile")
6358
and sys.platform.startswith(("linux", "android", "sunos")))
6459
_USE_CP_COPY_FILE_RANGE = hasattr(os, "copy_file_range")
65-
_HAS_FCOPYFILE = posix and hasattr(posix, "_fcopyfile") # macOS
60+
_HAS_FCOPYFILE = hasattr(os, "_fcopyfile") # macOS
6661

6762
# CMD defaults in Windows 10
6863
_WIN_DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC"
@@ -111,7 +106,7 @@ def _fastcopy_fcopyfile(fsrc, fdst, flags):
111106
raise _GiveupOnFastCopy(err) # not a regular file
112107

113108
try:
114-
posix._fcopyfile(infd, outfd, flags)
109+
os._fcopyfile(infd, outfd, flags)
115110
except OSError as err:
116111
err.filename = fsrc.name
117112
err.filename2 = fdst.name
@@ -332,7 +327,7 @@ def copyfile(src, dst, *, follow_symlinks=True):
332327
# macOS
333328
if _HAS_FCOPYFILE:
334329
try:
335-
_fastcopy_fcopyfile(fsrc, fdst, posix._COPYFILE_DATA)
330+
_fastcopy_fcopyfile(fsrc, fdst, os._COPYFILE_DATA)
336331
return dst
337332
except _GiveupOnFastCopy:
338333
pass
@@ -1489,7 +1484,7 @@ def disk_usage(path):
14891484
Returned values is a named tuple with attributes 'total', 'used' and
14901485
'free', which are the amount of total, used and free space, in bytes.
14911486
"""
1492-
total, free = nt._getdiskusage(path)
1487+
total, free = os._getdiskusage(path)
14931488
used = total - free
14941489
return _ntuple_diskusage(total, used, free)
14951490

0 commit comments

Comments
 (0)