Skip to content

Commit

Permalink
Return len of item written to OutStream
Browse files Browse the repository at this point in the history
Closes #682

Remove the piece of logic that handle `not isinstance(str)` it is a
leftover from Python 2, in pure Python, sys.stdout.write only accepts
str, therefore we have no reason not to do the same.
  • Loading branch information
Carreau committed Jun 14, 2021
1 parent bd43976 commit 1a50cda
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions ipykernel/iostream.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,21 @@ def _flush(self):
self.session.send(self.pub_thread, 'stream', content=content,
parent=self.parent_header, ident=self.topic)

def write(self, string):
def write(self, string: str) -> int:
"""Write to current stream after encoding if necessary
Returns
-------
len : int
number of items from input parameter written to stream.
"""

if not isinstance(string, str):
raise ValueError(
"TypeError: write() argument must be str, not {type(string)}"
)

if self.echo is not None:
try:
self.echo.write(string)
Expand All @@ -499,13 +513,10 @@ def write(self, string):
if self.pub_thread is None:
raise ValueError('I/O operation on closed file')
else:
# Make sure that we're handling unicode
if not isinstance(string, str):
string = string.decode(self.encoding, 'replace')

is_child = (not self._is_master_process())
# only touch the buffer in the IO thread to avoid races
self.pub_thread.schedule(lambda : self._buffer.write(string))
self.pub_thread.schedule(lambda: self._buffer.write(string))
if is_child:
# mp.Pool cannot be trusted to flush promptly (or ever),
# and this helps.
Expand All @@ -517,6 +528,8 @@ def write(self, string):
else:
self._schedule_flush()

return len(string)

def writelines(self, sequence):
if self.pub_thread is None:
raise ValueError('I/O operation on closed file')
Expand Down

0 comments on commit 1a50cda

Please sign in to comment.