2.2.2 Object Presentation

Python PEP

2.2.2 Object Presentation

In Python, there are three ways to generate a textual representation of an object: the repr() function (or equivalent back-tick syntax), the str()function, and the print statement. For most objects, the print statement is equivalent to the str() function, but it is possible to special-case printing to a FILE* if necessary; this should only be done if efficiency is identified as a problem and profiling suggests that creating a temporary string object to be written to a file is too expensive.

These handlers are all optional, and most types at most need to implement the tp_str and tp_repr handlers.

    reprfunc tp_repr;
    reprfunc tp_str;
    printfunc tp_print;

The tp_repr handler should return a string object containing a representation of the instance for which it is called. Here is a simple example:

static PyObject *
newdatatype_repr(newdatatypeobject * obj)
{
    return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}",
                               obj->obj_UnderlyingDatatypePtr->size);
}

If no tp_repr handler is specified, the interpreter will supply a representation that uses the type's tp_name and a uniquely-identifying value for the object.

The tp_str handler is to str() what the tp_repr handler described above is to repr(); that is, it is called when Python code calls str() on an instance of your object. Its implementation is very similar to the tp_repr function, but the resulting string is intended for human consumption. If tp_str is not specified, the tp_repr handler is used instead.

Here is a simple example:

static PyObject *
newdatatype_str(newdatatypeobject * obj)
{
    return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}",
                               obj->obj_UnderlyingDatatypePtr->size);
}

The print function will be called whenever Python needs to "print" an instance of the type. For example, if 'node' is an instance of type TreeNode, then the print function is called when Python code calls:

print node

There is a flags argument and one flag, Py_PRINT_RAW, and it suggests that you print without string quotes and possibly without interpreting escape sequences.

The print function receives a file object as an argument. You will likely want to write to that file object.

Here is a sample print function:

static int
newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
{
    if (flags & Py_PRINT_RAW) {
        fprintf(fp, "<{newdatatype object--size: %d}>",
                obj->obj_UnderlyingDatatypePtr->size);
    }
    else {
        fprintf(fp, "\"<{newdatatype object--size: %d}>\"",
                obj->obj_UnderlyingDatatypePtr->size);
    }
    return 0;
}

See About this document... for information on suggesting changes.