Skip to content

Commit 180ee43

Browse files
authored
gh-129005: Avoid copy in _pyio.FileIO.readinto() (#129324)
`os.read()` allocated and filled a buffer by calling `read(2)`, than that data was copied into the user provied buffer. Read directly into the caller's buffer instead by using `os.readinto()`. `os.readinto()` uses `PyObject_GetBuffer()` to make sure the passed in buffer is writeable and bytes-like, drop the manual check.
1 parent 4d0d24f commit 180ee43

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

Lib/_pyio.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -1692,13 +1692,14 @@ def readall(self):
16921692

16931693
return bytes(result)
16941694

1695-
def readinto(self, b):
1695+
def readinto(self, buffer):
16961696
"""Same as RawIOBase.readinto()."""
1697-
m = memoryview(b).cast('B')
1698-
data = self.read(len(m))
1699-
n = len(data)
1700-
m[:n] = data
1701-
return n
1697+
self._checkClosed()
1698+
self._checkReadable()
1699+
try:
1700+
return os.readinto(self._fd, buffer)
1701+
except BlockingIOError:
1702+
return None
17021703

17031704
def write(self, b):
17041705
"""Write bytes b to file, return number written.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Optimize ``_pyio.FileIO.readinto`` by avoiding unnecessary objects and copies using :func:`os.readinto`.

0 commit comments

Comments
 (0)