[Python-3000] TextIOWrapper.write(s:str) and bytes in py3k-struni
Christian Heimes
lists at cheimes.de
Sat Jul 14 15:36:04 CEST 2007
Hello!
I'm having some troubles with unit tests in the py3k-struni branch. Some
test like test_uu are failing because an io.TextIOWrapper instance's
write() method doesn't handle bytes. The method is defined as:
def write(self, s: str):
if self.closed:
raise ValueError("write to closed file")
# XXX What if we were just reading?
b = s.encode(self._encoding)
if isinstance(b, str):
b = bytes(b)
n = self.buffer.write(b)
if "\n" in s:
# XXX only if isatty
self.flush()
self._snapshot = self._decoder = None
return len(s)
The problematic lines are the lines from s.encode() to b = bytes(b). The
behavior is more than questionable. A bytes object doesn't have an
encode() method and str's encode method() always returns bytes. IMO the
write() method should be changed to:
def write(self, s: (str, bytes)):
if self.closed:
raise ValueError("write to closed file")
# XXX What if we were just reading?
if isinstance(s, basestring):
b = s.encode(self._encoding)
elif isinstance(s, bytes):
b = s
else:
b = bytes(b)
n = self.buffer.write(b)
if b"\n" in b:
# XXX only if isatty
self.flush()
self._snapshot = self._decoder = None
return len(s)
Or the write() should explictly raise a TypeError when it is not allowed
to handle bytes.
Christian
More information about the Python-3000
mailing list