0

As far as I know, python builtin functions are compiled from C source code and are built into the interpreter. Is there any way to find out where fuction code is situated to look at it in a disassembler?

Addition: For such function id() returns an address, isn't it? But when I look at it in the debugger it contains something far from asm code.

Addition 2: I have no source code because the interpreter is custom built.

1 Answers1

4

All built-ins are defined in the __builtin__ module, defined by the Python/bltinmodule.c source file.

To find a specific built-in, look at the module initialisation function, and the module methods table, then grep the Python source code for the definition of the attached function. Most functions in __builtin__ are defined in the same file.

For example the dir() function is found in the methods table as:

{"dir",             builtin_dir,        METH_VARARGS, dir_doc},

and builtin_dir is defined in the same file, delegating to PyObject_Dir():

static PyObject *
builtin_dir(PyObject *self, PyObject *args)
{
    PyObject *arg = NULL;

    if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
        return NULL;
    return PyObject_Dir(arg);
}

A quick grep through the Python sources leads to Objects/object.c, where PyObject_Dir() is implemented with several helper functions:

/* Implementation of dir() -- if obj is NULL, returns the names in the current
   (local) scope.  Otherwise, performs introspection of the object: returns a
   sorted list of attribute names (supposedly) accessible from the object
*/
PyObject *
PyObject_Dir(PyObject *obj)
{
    PyObject * result;

    if (obj == NULL)
        /* no object -- introspect the locals */
        result = _dir_locals();
    else
        /* object -- introspect the object */
        result = _dir_object(obj);

    assert(result == NULL || PyList_Check(result));

    if (result != NULL && PyList_Sort(result) != 0) {
        /* sorting the list failed */
        Py_DECREF(result);
        result = NULL;
    }

    return result;
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343