Search code examples
pythonpython-3.xfunctionbuilt-in

Implementation of 'print' in Python


I was just curious as to how built-in function 'print' might be working behind the scenes in Python3. So, the following code snippet is my attempt to write a print function of my own but I'm not sure if it accurately represents how the actual 'print' works:

import os
import sys
def my_print(*args, **kwargs):
    sep = kwargs.get('sep', ' ')
    end = kwargs.get('end', os.linesep)
    if end is None:
        end = os.linesep
    file = kwargs.get('file', sys.stdout)
    flush = kwargs.get('flush', False)
    file.write('%s%s' % (sep.join(str(arg) for arg in args), end))
    if flush:
        file.flush()

I would appreciate if anyone who knows how built-in 'print' works, assess the accuracy of my version and point out any deficiency.


Solution

  • print is a built-in function in Python 3. Most built-in functions are implemented in C (in the default CPython interpreter anyway), and print is no exception. The implementation is builtin_print_impl in Python/bltinmodule.c, which can be seen here: https://github.com/python/cpython/blob/v3.11.2/Python/bltinmodule.c#L1986

    The PyPy interpreter, on the other hand, is implemented in a subset of Python, so it has a print function written in Python in pypy/module/__builtin__/app_io.py, which can be seen here: https://foss.heptapod.net/pypy/pypy/-/blob/release-pypy3.9-v7.3.11/pypy/module/__builtin__/app_io.py#L87

    Here's the relevant code; it's fairly short:

    def print_(*args, sep=' ', end='\n', file=None, flush=False):
        r"""print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file:  a file-like object (stream); defaults to the current sys.stdout.
        sep:   string inserted between values, default a space.
        end:   string appended after the last value, default a newline.
        flush: whether to forcibly flush the stream.
        """
        fp = file
        if fp is None:
            fp = sys.stdout
            if fp is None:
                return
        if sep is None:
            sep = ' '
        if not isinstance(sep, str):
            raise TypeError("sep must be None or a string")
        if end is None:
            end = '\n'
        if not isinstance(end, str):
            raise TypeError("end must be None or a string")
        if len(args) == 1:
            fp.write(str(args[0]))
        else:
            for i, arg in enumerate(args):
                if i:
                    fp.write(sep)
                fp.write(str(arg))
        fp.write(end)
        if flush:
            fp.flush()