What is the difference between `>>> some_object` and `>>> print some_object` in the Python interpreter?
Asked Answered
K

5

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?

Kempe answered 18/8, 2011 at 22:1 Comment(0)
C
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!

Cashew answered 18/8, 2011 at 22:16 Comment(1)
For a None variable, typing the variable doesn't print anything. Yet print(repr(None)) gives None. How come?Margarettamargarette
C
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.

Christychristye answered 18/8, 2011 at 22:13 Comment(2)
Yes, x will be printed, because there is a print statement ;)Southport
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.Christychristye
S
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'
Southport answered 18/8, 2011 at 22:4 Comment(6)
Where is this documented? I couldn't find it.Hogan
@Hogan 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 !Southport
Haha, i really dunno where, but for sure somewhere in the documentation.Southport
You mean str(x) and repr(x), not x.str() and x.repr().Shalondashalt
or x.__str__() and x.__repr__()Branton
It was just a formatting problem, he couldn't enter backticks on his mobile device (as he said). I fixed it.Viradis
A
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 :).

Admix answered 18/8, 2011 at 22:22 Comment(0)
L
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.

Lomasi answered 24/12, 2011 at 0:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.