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.
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.
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.