Hexatonic Hexatonic - 5 months ago 8
Python Question

What built-in function is called when entering object in interactive Python shell?

It's nice to be able to enter an object in the shell, and get something back, e.g.,

>>>foo
I am foo


Usually, using
print(foo)
in a module script will yield the same result, as in the case above (I'm using Python 3.5). But often, with instances of complex classes, you can get wildly different outputs.

This raises the question, what exactly happens when you type an object name and hit enter in the interactive python shell? What built-in is called?

Example:

In module:

print(h5file)


Output:


tutorial1.h5 (File) 'Test file' Last modif.: 'Wed Jun 8 21:18:10 2016' Object Tree: / (RootGroup) 'Test file' /detector (Group) 'Detector information' /detector/readout (Table(0,)) 'Readout example'


Versus shell output


>>>h5file File(filename=tutorial1.h5, title='Test file', mode='w', root_uep='/', filters=Filters(complevel=0, shuffle=False, fletcher32=False, least_significant_digit=None)) / (RootGroup) 'Test file' /detector (Group) 'Detector information' /detector/readout (Table(0,)) 'Readout example' description := { "Country": UInt16Col(shape=(), dflt=0, pos=0), "Geo": UInt16Col(shape=(), dflt=0, pos=1), "HsCode": Int8Col(shape=(), dflt=0, pos=2), "Month": UInt16Col(shape=(), dflt=0, pos=3), "Quantity": UInt16Col(shape=(), dflt=0, pos=4),

Answer

print implicitly applies str() to each printed item to obtain a string, while the shell implicitly applies repr() to obtain a string. So it's the difference (if any) between an object's __str__() and __repr__() methods

>>> class A(object):
...    def __str__(self):
...        return "I'm friendly!"
...    def __repr__(self):
...        return "If different, I'm generally more verbose!"

>>> a = A()
>>> print(a)
I'm friendly!
>>> a
If different, I'm generally more verbose!

Note that I'm ignoring the possibility that the shell you use has overridden the default sys.displayhook function.

Comments