Search code examples
pythonstringprintingrepr

Which function does Python print use?


I've got an object which I print to the terminal, and it looks like this:

>>> print b
<p>„De neergang kan een duikvlucht worden.”</p>

So I then wondered from which function this the result is. So I tried the following:

>>> b.__repr__()
'<lxml.etree._XSLTResultTree object at 0x112c6a980>'
>>> b.__str__()
'\xe2\x80\x9eDe neergang kan een duikvlucht worden.\xe2\x80\x9d</p>'
>>> b.__unicode__()
'u'<p>\u201eDe neergang kan een duikvlucht worden.\u201d</p>'

As you can see, neither of these functions displays what the print statement shows. I always thought that print actually shows the result of either __repr__(), __str__() or __unicode__(), but that is clearly not the case.

So what does print actually call?


Solution

  • It is easy enough to check this sort of thing:

    >>> class C(object):
        def __repr__(self):
            print("repr called")
            return "repr"
        def __str__(self):
            print("str called")
            return "str"
        def __unicode__(self):
            print("unicode called")
            return "unicode"
    
    
    >>> print C()
    str called
    str
    >>> 
    

    In fact what happens internally is that print (as a function that is, I haven't checked the opcode though I think it is the same) calls PyFile_WriteObject with the Py_PRINT_RAW flag.

    int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)

    Write object obj to file object p. The only supported flag for flags is Py_PRINT_RAW; if given, the str() of the object is written instead of the repr(). Return 0 on success or -1 on failure; the appropriate exception will be set.