Let's go straight to your question.
Finding the source code for built-in Python functions?
The source code is located at Python/bltinmodule.c
To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>
, for instance, sorted()
is implemented in builtin_sorted
.
For your pleasure I'll post the implementation of sorted()
:
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* Keyword arguments are passed through list.sort() which will check
them. */
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = _PyObject_GetAttrId(newlist, &PyId_sort);
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
assert(nargs >= 1);
v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
As you may have noticed, that's not Python code, but C code.