Python中的'print'实现

4

我只是好奇Python3内置函数'print'的背后实现方式。因此,以下代码片段是我尝试编写自己的打印函数,但我不确定它是否准确地表示了实际的'print'如何工作:

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()

如果有人了解内置的“print”如何工作,请评估我的版本的准确性并指出任何不足之处,我将不胜感激。


1个回答

10

print是Python 3中的内置函数。大多数内置函数都是用C实现的(至少是在默认的CPython解释器中),而print也不例外。其实现位于Python/bltinmodule.c中的builtin_print_impl,可在此处查看:https://github.com/python/cpython/blob/v3.11.2/Python/bltinmodule.c#L1986

另一方面,PyPy解释器是用Python子集实现的,因此它有一个用Python编写的print函数,位于pypy/module/__builtin__/app_io.py中,可在此处查看:https://foss.heptapod.net/pypy/pypy/-/blob/release-pypy3.9-v7.3.11/pypy/module/__builtin__/app_io.py#L87

这是相关的代码; 相当简短:

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接