Skip to content
Advertisement

Using __str__ representation for printing objects in containers

I’ve noticed that when an instance with an overloaded __str__ method is passed to the print function as an argument, it prints as intended. However, when passing a container that contains one of those instances to print, it uses the __repr__ method instead. That is to say, print(x) displays the correct string representation of x, and print(x, y) works correctly, but print([x]) or print((x, y)) prints the __repr__ representation instead.

First off, why does this happen? Secondly, is there a way to correct that behavior of print in this circumstance?

Advertisement

Answer

The problem with the container using the objects’ __str__ would be the total ambiguity — what would it mean, say, if print L showed [1, 2]? L could be ['1, 2'] (a single item list whose string item contains a comma) or any of four 2-item lists (since each item can be a string or int). The ambiguity of type is common for print of course, but the total ambiguity for number of items (since each comma could be delimiting items or part of a string item) was the decisive consideration.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement