6

In the interpreter you can just write the name of an object e.g. a list a = [1, 2, 3, u"hellö"] at the interpreter prompt like this:

>>> a
[1, 2, 3, u'hell\xf6']

or you can do:

>>> print a
[1, 2, 3, u'hell\xf6']

which seems equivalent for lists. At the moment I am working with hdf5 to manage some data and I realized that there is a difference between the two methods mentioned above. Given:

with tables.openFile("tutorial.h5", mode = "w", title = "Some Title") as h5file:
    group = h5file.createGroup("/", 'node', 'Node information')
    tables.table = h5file.createTable(group, 'readout', Node, "Readout example")

The output of

print h5file

differs from

>>> h5file

So I was wondering if someone could explain Python's behavioral differences in these two cases?

5 Answers 5

8

Typing an object into the terminal calls __repr__(), which is for a detailed representation of the object you are printing (unambiguous). When you tell something to 'print', you are calling __str__() and therefore asking for something human readable.

Alex Martelli gave a great explanation here. Other responses in the thread might also illuminate the difference.

For example, take a look at datetime objects.

>>> import datetime
>>> now = datetime.datetime.now()

Compare...

>>> now
Out: datetime.datetime(2011, 8, 18, 15, 10, 29, 827606)

to...

>>> print now
Out: 2011-08-18 15:10:29.827606

Hopefully that makes it a little more clear!

1
  • For a None variable, typing the variable doesn't print anything. Yet print(repr(None)) gives None. How come?
    – flow2k
    Jun 13, 2018 at 19:17
2

The interactive interpreter will print the result of each expression typed into it. (Since statements do not evaluate, but rather execute, this printing behavior does not apply to statements such as print itself, loops, etc.)

Proof that repr() is used by the interactive interpreter as stated by Niklas Rosenstein (using a 2.6 interpreter):

>>> class Foo:
...   def __repr__(self):
...     return 'repr Foo'
...   def __str__(self):
...     return 'str Foo'
...
>>> x = Foo()
>>> x
repr Foo
>>> print x
str Foo

So while the print statement may be unnecessary in the interactive interpreter (unless you need str and not repr), the non-interactive interpreter does not do this. Placing the above code in a file and running the file will result in nothing being printed.

2
  • Yes, x will be printed, because there is a print statement ;)
    – Niklas R
    Aug 19, 2011 at 6:06
  • Ha, that's funny. I edited the answer to include the print x statement to show that one uses str and the other repr and forgot to amend the final paragraph.
    – wberry
    Aug 19, 2011 at 17:23
1

The print statement always calls x.__str__() method while (only in the interactive interpeter) simply calling a variable the objects x.__repr__() method ia called.

>>> '\x02agh'
'\x02agh'
>>> print '\x02agh'
'agh'
6
  • Where is this documented? I couldn't find it.
    – jtbandes
    Aug 18, 2011 at 22:05
  • @jtbandes Don't know where, but you can test it yourself. PS: Can somebody pleaso format the inline codes right ? It doesnt work on a mobile device. Thanks !
    – Niklas R
    Aug 18, 2011 at 22:07
  • Haha, i really dunno where, but for sure somewhere in the documentation.
    – Niklas R
    Aug 18, 2011 at 22:08
  • 1
    You mean str(x) and repr(x), not x.str() and x.repr(). Aug 18, 2011 at 22:10
  • or x.__str__() and x.__repr__()
    – Evpok
    Aug 18, 2011 at 22:12
0

Look at Python documentation at: http://docs.python.org/reference/datamodel.html#object.repr

object.repr(self)

Called by the repr() built-in function and by string conversions

(reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines repr() but not str(), then repr() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the

representation is information-rich and unambiguous.

object.str(self)

Called by the str() built-in function and by the print statement

to compute the “informal” string representation of an object. This differs from repr() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

Example:

>>> class A():
...    def __repr__(self): return "repr!"
...    def __str__(self): return "str!"
... 
>>> a = A()
>>> a
repr!
>>> print(a)
str!
>>> class B():
...    def __repr__(self): return "repr!"
... 
>>> class C():
...    def __str__(self): return "str!"
... 
>>> b = B()
>>> b
repr!
>>> print(b)
repr!
>>> c = C()
>>> c
<__main__.C object at 0x7f7162efb590>
>>> print(c)
str!

Print function prints the console every arguments __str__. Like print(str(obj)).

But in interactive console, it print function's return value's __repr__. And if __str__ not defined, __repr__ could be used instead.

Ideally, __repr__ means, we should just use that representation to reproduce that object. It shouldn't be identical between different classes, or object's that represents different values, For example, datetime.time:

But __str__ (what we get from str(obj)) should seem nice, because we show it to user.

>>> a = datetime.time(16, 42, 3)
>>> repr(a)
'datetime.time(16, 42, 3)'
>>> str(a)
'16:42:03' #We dont know what it is could be just print:
>>> print("'16:42:03'")
'16:42:03'

And, sorry for bad English :).

0

print(variable) equals to print(str(variable))

whereas

variable equals to print(repr(variable))

Obviously, the __repr__ and __str__ method of the object h5file produce different results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.