printing list, is this a bug?

W

William Chang

Is the different behavior between __repr__ and __str__ intentional
when it comes to printing lists? Basically I want to print out a list
with elements of my own class, but when I overwrite __str__, __str__
doesn't get called but if I overwrite __repr__, __repr__ will get
called. Is this a bug?



For example:
.... def __str__(self):
.... return "String Element"
....
a = [StrElement(), StrElement()]
print a
<__main__.StrElement said:
print StrElement()
String Element



But if overwrite __repr__:
.... def __repr__(self):
.... return "Repr Element"
....
b = [ReprElement(), ReprElement()]
print b
[Repr Element, Repr Element]
Repr Element
 
R

Robert Kern

William said:
Is the different behavior between __repr__ and __str__ intentional
when it comes to printing lists? Basically I want to print out a list
with elements of my own class, but when I overwrite __str__, __str__
doesn't get called but if I overwrite __repr__, __repr__ will get
called. Is this a bug?

No, it's deliberate design. The string representation of a list object, either
list.__str__() or list.__repr__(), uses the __repr__() of its contained objects.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
D

Dan Bishop

Is the different behavior between __repr__ and __str__ intentional
when it comes to printing lists? Basically I want to print out a list
with elements of my own class, but when I overwrite __str__, __str__
doesn't get called but if I overwrite __repr__, __repr__ will get
called. Is this a bug?
...

As has been mentioned, this was a deliberate design decision. Partly
to make things like str(['a', 'b, c']) less confusing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top