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?
The problem with the container using the objects’
__str__would be the total ambiguity — what would it mean, say, ifprint Lshowed[1, 2]?Lcould 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 forprintof 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.