Issue #17003: Unified the size argument names in the io module with common

practice.
This commit is contained in:
Serhiy Storchaka 2013-09-16 23:18:10 +03:00
parent b3955fe0c4
commit 3c41154331
3 changed files with 113 additions and 107 deletions

View file

@ -283,10 +283,10 @@ I/O Base Classes
Return ``True`` if the stream can be read from. If False, :meth:`read` Return ``True`` if the stream can be read from. If False, :meth:`read`
will raise :exc:`OSError`. will raise :exc:`OSError`.
.. method:: readline(limit=-1) .. method:: readline(size=-1)
Read and return one line from the stream. If *limit* is specified, at Read and return one line from the stream. If *size* is specified, at
most *limit* bytes will be read. most *size* bytes will be read.
The line terminator is always ``b'\n'`` for binary files; for text files, The line terminator is always ``b'\n'`` for binary files; for text files,
the *newlines* argument to :func:`open` can be used to select the line the *newlines* argument to :func:`open` can be used to select the line
@ -366,14 +366,14 @@ I/O Base Classes
In addition to the attributes and methods from :class:`IOBase`, In addition to the attributes and methods from :class:`IOBase`,
:class:`RawIOBase` provides the following methods: :class:`RawIOBase` provides the following methods:
.. method:: read(n=-1) .. method:: read(size=-1)
Read up to *n* bytes from the object and return them. As a convenience, Read up to *size* bytes from the object and return them. As a convenience,
if *n* is unspecified or -1, :meth:`readall` is called. Otherwise, if *size* is unspecified or -1, :meth:`readall` is called. Otherwise,
only one system call is ever made. Fewer than *n* bytes may be only one system call is ever made. Fewer than *size* bytes may be
returned if the operating system call returns fewer than *n* bytes. returned if the operating system call returns fewer than *size* bytes.
If 0 bytes are returned, and *n* was not 0, this indicates end of file. If 0 bytes are returned, and *size* was not 0, this indicates end of file.
If the object is in non-blocking mode and no bytes are available, If the object is in non-blocking mode and no bytes are available,
``None`` is returned. ``None`` is returned.
@ -442,10 +442,10 @@ I/O Base Classes
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: read(n=-1) .. method:: read(size=-1)
Read and return up to *n* bytes. If the argument is omitted, ``None``, or Read and return up to *size* bytes. If the argument is omitted, ``None``,
negative, data is read and returned until EOF is reached. An empty or negative, data is read and returned until EOF is reached. An empty
:class:`bytes` object is returned if the stream is already at EOF. :class:`bytes` object is returned if the stream is already at EOF.
If the argument is positive, and the underlying raw stream is not If the argument is positive, and the underlying raw stream is not
@ -457,9 +457,9 @@ I/O Base Classes
A :exc:`BlockingIOError` is raised if the underlying raw stream is in A :exc:`BlockingIOError` is raised if the underlying raw stream is in
non blocking-mode, and has no data available at the moment. non blocking-mode, and has no data available at the moment.
.. method:: read1(n=-1) .. method:: read1(size=-1)
Read and return up to *n* bytes, with at most one call to the underlying Read and return up to *size* bytes, with at most one call to the underlying
raw stream's :meth:`~RawIOBase.read` method. This can be useful if you raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
are implementing your own buffering on top of a :class:`BufferedIOBase` are implementing your own buffering on top of a :class:`BufferedIOBase`
object. object.
@ -606,21 +606,21 @@ than raw I/O does.
:class:`BufferedReader` provides or overrides these methods in addition to :class:`BufferedReader` provides or overrides these methods in addition to
those from :class:`BufferedIOBase` and :class:`IOBase`: those from :class:`BufferedIOBase` and :class:`IOBase`:
.. method:: peek([n]) .. method:: peek([size])
Return bytes from the stream without advancing the position. At most one Return bytes from the stream without advancing the position. At most one
single read on the raw stream is done to satisfy the call. The number of single read on the raw stream is done to satisfy the call. The number of
bytes returned may be less or more than requested. bytes returned may be less or more than requested.
.. method:: read([n]) .. method:: read([size])
Read and return *n* bytes, or if *n* is not given or negative, until EOF Read and return *size* bytes, or if *size* is not given or negative, until
or if the read call would block in non-blocking mode. EOF or if the read call would block in non-blocking mode.
.. method:: read1(n) .. method:: read1(size)
Read and return up to *n* bytes with only one call on the raw stream. If Read and return up to *size* bytes with only one call on the raw stream.
at least one byte is buffered, only buffered bytes are returned. If at least one byte is buffered, only buffered bytes are returned.
Otherwise, one raw stream read call is made. Otherwise, one raw stream read call is made.
@ -739,17 +739,17 @@ Text I/O
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: read(n) .. method:: read(size)
Read and return at most *n* characters from the stream as a single Read and return at most *size* characters from the stream as a single
:class:`str`. If *n* is negative or ``None``, reads until EOF. :class:`str`. If *size* is negative or ``None``, reads until EOF.
.. method:: readline(limit=-1) .. method:: readline(size=-1)
Read until newline or EOF and return a single ``str``. If the stream is Read until newline or EOF and return a single ``str``. If the stream is
already at EOF, an empty string is returned. already at EOF, an empty string is returned.
If *limit* is specified, at most *limit* characters will be read. If *size* is specified, at most *size* characters will be read.
.. method:: seek(offset, whence=SEEK_SET) .. method:: seek(offset, whence=SEEK_SET)

View file

@ -457,11 +457,11 @@ class IOBase(metaclass=abc.ABCMeta):
### Readline[s] and writelines ### ### Readline[s] and writelines ###
def readline(self, limit=-1): def readline(self, size=-1):
r"""Read and return a line of bytes from the stream. r"""Read and return a line of bytes from the stream.
If limit is specified, at most limit bytes will be read. If size is specified, at most size bytes will be read.
Limit should be an int. Size should be an int.
The line terminator is always b'\n' for binary files; for text The line terminator is always b'\n' for binary files; for text
files, the newlines argument to open can be used to select the line files, the newlines argument to open can be used to select the line
@ -474,18 +474,18 @@ class IOBase(metaclass=abc.ABCMeta):
if not readahead: if not readahead:
return 1 return 1
n = (readahead.find(b"\n") + 1) or len(readahead) n = (readahead.find(b"\n") + 1) or len(readahead)
if limit >= 0: if size >= 0:
n = min(n, limit) n = min(n, size)
return n return n
else: else:
def nreadahead(): def nreadahead():
return 1 return 1
if limit is None: if size is None:
limit = -1 size = -1
elif not isinstance(limit, int): elif not isinstance(size, int):
raise TypeError("limit must be an integer") raise TypeError("size must be an integer")
res = bytearray() res = bytearray()
while limit < 0 or len(res) < limit: while size < 0 or len(res) < size:
b = self.read(nreadahead()) b = self.read(nreadahead())
if not b: if not b:
break break
@ -544,17 +544,17 @@ class RawIOBase(IOBase):
# primitive operation, but that would lead to nasty recursion in case # primitive operation, but that would lead to nasty recursion in case
# a subclass doesn't implement either.) # a subclass doesn't implement either.)
def read(self, n=-1): def read(self, size=-1):
"""Read and return up to n bytes, where n is an int. """Read and return up to size bytes, where size is an int.
Returns an empty bytes object on EOF, or None if the object is Returns an empty bytes object on EOF, or None if the object is
set not to block and has no data to read. set not to block and has no data to read.
""" """
if n is None: if size is None:
n = -1 size = -1
if n < 0: if size < 0:
return self.readall() return self.readall()
b = bytearray(n.__index__()) b = bytearray(size.__index__())
n = self.readinto(b) n = self.readinto(b)
if n is None: if n is None:
return None return None
@ -612,8 +612,8 @@ class BufferedIOBase(IOBase):
implementation, but wrap one. implementation, but wrap one.
""" """
def read(self, n=None): def read(self, size=None):
"""Read and return up to n bytes, where n is an int. """Read and return up to size bytes, where size is an int.
If the argument is omitted, None, or negative, reads and If the argument is omitted, None, or negative, reads and
returns all data until EOF. returns all data until EOF.
@ -632,9 +632,9 @@ class BufferedIOBase(IOBase):
""" """
self._unsupported("read") self._unsupported("read")
def read1(self, n=None): def read1(self, size=None):
"""Read up to n bytes with at most one read() system call, """Read up to size bytes with at most one read() system call,
where n is an int. where size is an int.
""" """
self._unsupported("read1") self._unsupported("read1")
@ -822,24 +822,24 @@ class BytesIO(BufferedIOBase):
""" """
return memoryview(self._buffer) return memoryview(self._buffer)
def read(self, n=None): def read(self, size=None):
if self.closed: if self.closed:
raise ValueError("read from closed file") raise ValueError("read from closed file")
if n is None: if size is None:
n = -1 size = -1
if n < 0: if size < 0:
n = len(self._buffer) size = len(self._buffer)
if len(self._buffer) <= self._pos: if len(self._buffer) <= self._pos:
return b"" return b""
newpos = min(len(self._buffer), self._pos + n) newpos = min(len(self._buffer), self._pos + size)
b = self._buffer[self._pos : newpos] b = self._buffer[self._pos : newpos]
self._pos = newpos self._pos = newpos
return bytes(b) return bytes(b)
def read1(self, n): def read1(self, size):
"""This is the same as read. """This is the same as read.
""" """
return self.read(n) return self.read(size)
def write(self, b): def write(self, b):
if self.closed: if self.closed:
@ -942,18 +942,18 @@ class BufferedReader(_BufferedIOMixin):
self._read_buf = b"" self._read_buf = b""
self._read_pos = 0 self._read_pos = 0
def read(self, n=None): def read(self, size=None):
"""Read n bytes. """Read size bytes.
Returns exactly n bytes of data unless the underlying raw IO Returns exactly size bytes of data unless the underlying raw IO
stream reaches EOF or if the call would block in non-blocking stream reaches EOF or if the call would block in non-blocking
mode. If n is negative, read until EOF or until read() would mode. If size is negative, read until EOF or until read() would
block. block.
""" """
if n is not None and n < -1: if size is not None and size < -1:
raise ValueError("invalid number of bytes to read") raise ValueError("invalid number of bytes to read")
with self._read_lock: with self._read_lock:
return self._read_unlocked(n) return self._read_unlocked(size)
def _read_unlocked(self, n=None): def _read_unlocked(self, n=None):
nodata_val = b"" nodata_val = b""
@ -1013,7 +1013,7 @@ class BufferedReader(_BufferedIOMixin):
self._read_pos = 0 self._read_pos = 0
return out[:n] if out else nodata_val return out[:n] if out else nodata_val
def peek(self, n=0): def peek(self, size=0):
"""Returns buffered bytes without advancing the position. """Returns buffered bytes without advancing the position.
The argument indicates a desired minimal number of bytes; we The argument indicates a desired minimal number of bytes; we
@ -1021,7 +1021,7 @@ class BufferedReader(_BufferedIOMixin):
than self.buffer_size. than self.buffer_size.
""" """
with self._read_lock: with self._read_lock:
return self._peek_unlocked(n) return self._peek_unlocked(size)
def _peek_unlocked(self, n=0): def _peek_unlocked(self, n=0):
want = min(n, self.buffer_size) want = min(n, self.buffer_size)
@ -1039,18 +1039,18 @@ class BufferedReader(_BufferedIOMixin):
self._read_pos = 0 self._read_pos = 0
return self._read_buf[self._read_pos:] return self._read_buf[self._read_pos:]
def read1(self, n): def read1(self, size):
"""Reads up to n bytes, with at most one read() system call.""" """Reads up to size bytes, with at most one read() system call."""
# Returns up to n bytes. If at least one byte is buffered, we # Returns up to size bytes. If at least one byte is buffered, we
# only return buffered bytes. Otherwise, we do one raw read. # only return buffered bytes. Otherwise, we do one raw read.
if n < 0: if size < 0:
raise ValueError("number of bytes to read must be positive") raise ValueError("number of bytes to read must be positive")
if n == 0: if size == 0:
return b"" return b""
with self._read_lock: with self._read_lock:
self._peek_unlocked(1) self._peek_unlocked(1)
return self._read_unlocked( return self._read_unlocked(
min(n, len(self._read_buf) - self._read_pos)) min(size, len(self._read_buf) - self._read_pos))
def tell(self): def tell(self):
return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
@ -1184,10 +1184,10 @@ class BufferedRWPair(BufferedIOBase):
self.reader = BufferedReader(reader, buffer_size) self.reader = BufferedReader(reader, buffer_size)
self.writer = BufferedWriter(writer, buffer_size) self.writer = BufferedWriter(writer, buffer_size)
def read(self, n=None): def read(self, size=None):
if n is None: if size is None:
n = -1 size = -1
return self.reader.read(n) return self.reader.read(size)
def readinto(self, b): def readinto(self, b):
return self.reader.readinto(b) return self.reader.readinto(b)
@ -1195,11 +1195,11 @@ class BufferedRWPair(BufferedIOBase):
def write(self, b): def write(self, b):
return self.writer.write(b) return self.writer.write(b)
def peek(self, n=0): def peek(self, size=0):
return self.reader.peek(n) return self.reader.peek(size)
def read1(self, n): def read1(self, size):
return self.reader.read1(n) return self.reader.read1(size)
def readable(self): def readable(self):
return self.reader.readable() return self.reader.readable()
@ -1265,23 +1265,23 @@ class BufferedRandom(BufferedWriter, BufferedReader):
# Use seek to flush the read buffer. # Use seek to flush the read buffer.
return BufferedWriter.truncate(self, pos) return BufferedWriter.truncate(self, pos)
def read(self, n=None): def read(self, size=None):
if n is None: if size is None:
n = -1 size = -1
self.flush() self.flush()
return BufferedReader.read(self, n) return BufferedReader.read(self, size)
def readinto(self, b): def readinto(self, b):
self.flush() self.flush()
return BufferedReader.readinto(self, b) return BufferedReader.readinto(self, b)
def peek(self, n=0): def peek(self, size=0):
self.flush() self.flush()
return BufferedReader.peek(self, n) return BufferedReader.peek(self, size)
def read1(self, n): def read1(self, size):
self.flush() self.flush()
return BufferedReader.read1(self, n) return BufferedReader.read1(self, size)
def write(self, b): def write(self, b):
if self._read_buf: if self._read_buf:
@ -1301,11 +1301,11 @@ class TextIOBase(IOBase):
are immutable. There is no public constructor. are immutable. There is no public constructor.
""" """
def read(self, n=-1): def read(self, size=-1):
"""Read at most n characters from stream, where n is an int. """Read at most size characters from stream, where size is an int.
Read from underlying buffer until we have n characters or we hit EOF. Read from underlying buffer until we have size characters or we hit EOF.
If n is negative or omitted, read until EOF. If size is negative or omitted, read until EOF.
Returns a string. Returns a string.
""" """
@ -1909,16 +1909,16 @@ class TextIOWrapper(TextIOBase):
encoder.reset() encoder.reset()
return cookie return cookie
def read(self, n=None): def read(self, size=None):
self._checkReadable() self._checkReadable()
if n is None: if size is None:
n = -1 size = -1
decoder = self._decoder or self._get_decoder() decoder = self._decoder or self._get_decoder()
try: try:
n.__index__ size.__index__
except AttributeError as err: except AttributeError as err:
raise TypeError("an integer is required") from err raise TypeError("an integer is required") from err
if n < 0: if size < 0:
# Read everything. # Read everything.
result = (self._get_decoded_chars() + result = (self._get_decoded_chars() +
decoder.decode(self.buffer.read(), final=True)) decoder.decode(self.buffer.read(), final=True))
@ -1926,12 +1926,12 @@ class TextIOWrapper(TextIOBase):
self._snapshot = None self._snapshot = None
return result return result
else: else:
# Keep reading chunks until we have n characters to return. # Keep reading chunks until we have size characters to return.
eof = False eof = False
result = self._get_decoded_chars(n) result = self._get_decoded_chars(size)
while len(result) < n and not eof: while len(result) < size and not eof:
eof = not self._read_chunk() eof = not self._read_chunk()
result += self._get_decoded_chars(n - len(result)) result += self._get_decoded_chars(size - len(result))
return result return result
def __next__(self): def __next__(self):
@ -1943,13 +1943,13 @@ class TextIOWrapper(TextIOBase):
raise StopIteration raise StopIteration
return line return line
def readline(self, limit=None): def readline(self, size=None):
if self.closed: if self.closed:
raise ValueError("read from closed file") raise ValueError("read from closed file")
if limit is None: if size is None:
limit = -1 size = -1
elif not isinstance(limit, int): elif not isinstance(size, int):
raise TypeError("limit must be an integer") raise TypeError("size must be an integer")
# Grab all the decoded text (we will rewind any extra bits later). # Grab all the decoded text (we will rewind any extra bits later).
line = self._get_decoded_chars() line = self._get_decoded_chars()
@ -2008,8 +2008,8 @@ class TextIOWrapper(TextIOBase):
endpos = pos + len(self._readnl) endpos = pos + len(self._readnl)
break break
if limit >= 0 and len(line) >= limit: if size >= 0 and len(line) >= size:
endpos = limit # reached length limit endpos = size # reached length size
break break
# No line ending seen yet - get more data' # No line ending seen yet - get more data'
@ -2024,8 +2024,8 @@ class TextIOWrapper(TextIOBase):
self._snapshot = None self._snapshot = None
return line return line
if limit >= 0 and endpos > limit: if size >= 0 and endpos > size:
endpos = limit # don't exceed limit endpos = size # don't exceed size
# Rewind _decoded_chars to just after the line ending we found. # Rewind _decoded_chars to just after the line ending we found.
self._rewind_decoded_chars(len(line) - endpos) self._rewind_decoded_chars(len(line) - endpos)

View file

@ -49,6 +49,12 @@ IDLE
- Issue #18988: The "Tab" key now works when a word is already autocompleted. - Issue #18988: The "Tab" key now works when a word is already autocompleted.
Documentation
-------------
- Issue #17003: Unified the size argument names in the io module with common
practice.
What's New in Python 3.4.0 Alpha 2? What's New in Python 3.4.0 Alpha 2?
=================================== ===================================