Make print() use a single write() call

I like the idea of joining print() arguments + end argument into a single string to only call file.write() once.

The usual case is that a line is around 100 characters. The change can have a negative impact on performance if the line is very long (ex: 1 MB): print(long_line) would compute long_line + '\n' which requires to duplicate the memory (double memory usage) just to add a newline character at the end. Maybe we can implement an advanced mode using writev() to pass an array of bytes strings, but that can be addressed later.

If print() arguments contain newlines, I still consider that it’s a good thing to only call file.write() once. I don’t think that we should split the strings at newline to call file.write() once per line.

I don’t think that it’s a good idea to write end if formatting an object as str raised an exception.

Instead, I would propose:

import sys

def atomic_print(*objects, sep=' ', end='\n', flush=True, file=None):
    if sep is None:
        sep = ' '
    elif not isinstance(sep, str):
        raise TypeError(f"sep must be None or a string, not {type(sep).__name}")

    if end is None:
        end = '\n'
    elif not isinstance(end, str):
        raise TypeError(f"end must be None or a string, not {type(end).__name}")

    if file is None:
        file = sys.stdout
        if file is None:
            return

    parts = []
    try:
        for obj in objects:
            if parts:
                parts.append(sep)
            arg = str(obj)
            parts.append(arg)
        parts.append(end)
    finally:
        # call write even if str(obj) raised an exception
        try:
            line = ''.join(parts)
        except:
            # most likely error: MemoryError
            for arg in parts:
                file.write(arg)
            if flush:
                file.flush()
            raise

        file.write(line)
        if flush:
            file.flush()

Note: the code can be micro-optimized if sep, end and/or line are empty strings. But I prefer to keep my code short here :slight_smile:

Example:

class BadStr:
    def __str__(self):
        raise Exception("not good")

end = '\\n\n'
atomic_print('Hello', 'World!', end=end)
try:
    atomic_print('before error', BadStr(), end=end)
except Exception:
    pass
atomic_print('exit', end=end)

Output:

Hello World!\n
before error exit\n

3 lines are written, but only 2 lines (and 2 end) are displayed: the second print() doesn’t write the end since BadStr() raised Exception.

1 Like