Skip to content

Commit a1a1cb7

Browse files
committed
pythongh-90102: Shortcut isatty in _pyio open()
1 parent c066bf5 commit a1a1cb7

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

Lib/_pyio.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
238238
result = raw
239239
try:
240240
line_buffering = False
241-
if buffering == 1 or buffering < 0 and raw.isatty():
241+
if buffering == 1 or buffering < 0 and raw._isatty_openonly():
242242
buffering = -1
243243
line_buffering = True
244244
if buffering < 0:
@@ -1794,6 +1794,19 @@ def isatty(self):
17941794
self._checkClosed()
17951795
return os.isatty(self._fd)
17961796

1797+
def _isatty_openonly(self):
1798+
"""Checks whether the file is a TTY using an open-only optimization.
1799+
Normally isatty always makes a system call. In the case of open() there
1800+
is a _inside the same python call_ stat result which we can use to
1801+
skip that system call for non-character files. Outside of that context
1802+
this is subject to TOCTOU issues (the FD has been returned to user code
1803+
and arbitrary syscalls could have happened).
1804+
"""
1805+
if (self._stat_atopen is not None and
1806+
not stat.S_ISCHR(self._stat_atopen.st_mode)):
1807+
return True
1808+
return os.isatty(self._fd)
1809+
17971810
@property
17981811
def closefd(self):
17991812
"""True if the file descriptor will be closed by close()."""

0 commit comments

Comments
 (0)