为什么模块数学被称为“内建”?

2024-06-28 20:30:04 发布

您现在位置:Python中文网/ 问答频道 /正文

AFAIK,Pythonbuiltins指的是__builtins__中包含的那些异常和函数:

>>> import builtins  # import __builtin__ in Python 2
>>> dir(builtins)  # dir(__builtin__) for Python 2
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
...many more...
'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed',
'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum',
'super', 'tuple', 'type', 'vars', 'zip']

但是看看下面的代码(Python2和3都给出了相同的结果):

^{pr2}$

在最后一行,模块math被称为built-in。为什么?模块math和其他模块如threading有什么区别?在


Tags: 模块函数inimportfordirmathattributeerror
3条回答

从文档(./Doc/library/stdtypes.rst)中:

Modules

...

Modules built into the interpreter are written like this: <module 'sys' (built-in)>. If loaded from a file, they are written as <module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>.

相关代码位于模块对象的repr()函数中:

static PyObject *
module_repr(PyModuleObject *m)
{
    char *name;
    char *filename;

    name = PyModule_GetName((PyObject *)m);
    if (name == NULL) {
        PyErr_Clear();
        name = "?";
    }
    filename = PyModule_GetFilename((PyObject *)m);
    if (filename == NULL) {
        PyErr_Clear();
        return PyString_FromFormat("<module '%s' (built-in)>", name);
    }
    return PyString_FromFormat("<module '%s' from '%s'>", name, filename);
}

在您的例子中,math模块在构建库时包含在主Python库本身(libpython2.7.{so,dll,dylib})中。这是可能的,因为模块是用C编写的,而不是用纯Python编写的。其他类似的模块包括sys和{}。在

Python docs有这样的话:

The bulk of the library, however, consists of a collection of modules. There are many ways to dissect this collection. Some modules are written in C and built in to the Python interpreter; others are written in Python and imported in source form.

math模块是用C语言编写的,它被构建到解释器中,而threading是用Python编写的,并在源代码中导入。在

相关问题 更多 >