Skip to content

gh-134706: Return bytes written from codecs.Stream(Reader)Writer.write() #134708

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Doc/library/codecs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,9 @@ compatible with the Python codec registry.

Writes the object's contents encoded to the stream.

.. versionchanged:: next
Returns the number of characters or bytes written to the stream.


.. method:: writelines(list)

Expand Down
2 changes: 1 addition & 1 deletion Lib/codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ def write(self, object):
""" Writes the object's contents encoded to self.stream.
"""
data, consumed = self.encode(object, self.errors)
self.stream.write(data)
return self.stream.write(data)

def writelines(self, list):

Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1985,6 +1985,11 @@ class StreamWriterTest(unittest.TestCase):
def setUp(self):
self.writer = codecs.getwriter('utf-8')

def test_write(self):
bio = io.BytesIO()
self.assertEqual(self.writer(bio).write("Hällo"), 6)
self.assertEqual(bio.getvalue(), b'H\xc3\xa4llo')

def test_copy(self):
f = self.writer(Queue(b''))
with self.assertRaisesRegex(TypeError, 'StreamWriter'):
Expand All @@ -2006,6 +2011,12 @@ def setUp(self):
self.reader = codecs.getreader('latin1')
self.writer = codecs.getwriter('utf-8')

def test_write(self):
bio = io.BytesIO()
f = codecs.StreamReaderWriter(bio, self.reader, self.writer)
self.assertEqual(f.write("Hällo"), 6)
self.assertEqual(bio.getvalue(), b'H\xc3\xa4llo')

def test_copy(self):
f = codecs.StreamReaderWriter(Queue(b''), self.reader, self.writer)
with self.assertRaisesRegex(TypeError, 'StreamReaderWriter'):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:meth:`codecs.StreamWriter.write` and :meth:`!codecs.StreamReaderWriter.write`
now correctly return the number of characters or bytes written instead of
returning ``None``.
Loading