python内置函数源码
时间: 2023-10-17 19:17:49 浏览: 148
Python内置函数是用C语言实现的,其源代码存储在Python解释器的安装目录下的“Modules”文件夹中。以下是一些内置函数的源代码示例:
1. print函数
```c
static PyObject *
builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
{
...
if (PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
goto error;
...
}
```
2. len函数
```c
static PyObject *
builtin_len(PyObject *self, PyObject *v)
{
...
Py_ssize_t res = PyObject_Size(v);
...
}
```
3. range函数
```c
static PyObject *
builtin_range(PyObject *self, PyObject *args, PyObject *kwds)
{
...
PyObject *start = PyLong_FromLong(0);
PyObject *step = PyLong_FromLong(1);
...
if (!_PyArg_NoKeywords("range()", kwds))
goto err;
if (PyTuple_Size(args) > 3) {
PyErr_SetString(PyExc_TypeError,
"range expected at most 3 arguments, got %zd",
PyTuple_GET_SIZE(args));
goto err;
}
...
PyObject *stop = PyTuple_GET_ITEM(args, n);
...
}
```
这些源代码只是简化的示例,实际上每个内置函数的源代码都非常复杂。如果您希望深入了解Python内置函数的实现方式,建议您查看Python解释器的源代码。
阅读全文