3

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.

deniz
  • 117
  • 2
  • 7
  • Related: [Is it possible to “hack” Python's print function?](https://stackoverflow.com/questions/49271750/is-it-possible-to-hack-pythons-print-function) – pault Nov 25 '19 at 21:03

1 Answers1

8

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 in Python/bltinmodule.c, which can be seen here: https://github.com/python/cpython/blob/v3.8.0/Python/bltinmodule.c#L1821

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://bitbucket.org/pypy/pypy/src/5da45ced70e515f94686be0df47c59abd1348ebc/pypy/module/builtin/app_io.py#lines-59

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

def print_(*args, **kwargs):
    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 = kwargs.pop("file", None)
    if fp is None:
        fp = sys.stdout
        if fp is None:
            return
    def write(data):
        fp.write(str(data))
    sep = kwargs.pop("sep", None)
    if sep is not None:
        if not isinstance(sep, str):
            raise TypeError("sep must be None or a string")
    end = kwargs.pop("end", None)
    if end is not None:
        if not isinstance(end, str):
            raise TypeError("end must be None or a string")
    flush = kwargs.pop('flush', None)
    if kwargs:
        raise TypeError("invalid keyword arguments to print()")
    if sep is None:
        sep = " "
    if end is None:
        end = "\n"
    for i, arg in enumerate(args):
        if i:
            write(sep)
        write(arg)
    write(end)
    if flush:
        fp.flush()
nneonneo
  • 162,933
  • 34
  • 285
  • 360