Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing lists with __str__ and __repr__ in Python

I have a class Player which puts created objects in a List:

class Player:
    all = []
    def __init__(self, name: str):
        self.name = name
        Player.all.append(self)

    def __repr__(self):
        return f"N: {self.name}"

I wanted to print the list of the following objects using repr:

player1 = Player("p1")
player2 = Player("p2")
player3 = Player("p3")

print(Player.all)

I got what i was expecting:
[N: p1, N: p2, N: p3]
Printing the same list using str,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    def __str__(self):
        return f"N: {self.name}"

gave me this:
[<classes.Player object at 0x00000213939B1AF0>, <classes.Player object at 0x00000213939B1AC0>, <classes.Player object at 0x00000213939B1B80>]

But printing only one object, instead of the list, using str gave me something usable again:
print(player1)
N: p1

From what i understand, i can only print lists by using repr.
But, why?

>Solution :

lists don’t have a str form separate from their repr form (any class that implements __repr__ but not __str__ uses the __repr__ when __str__ is needed), and their repr form recursively prints the repr of the contained objects. repr makes sense for lists; if all the objects involved implement a canonical repr (one which can be pasted back into an interpreter to reproduce an equivalent object, unlike the form you’re using), then the repr of the list itself can also be pasted back in to reproduce it.

str form is not nearly so obvious; there’s no single obvious "human-friendly" (as opposed to programmer-friendly) display format for a list, so Python refuses the temptation to guess and leaves it up to you to format the content of lists for human-friendly display as you like.


The canonical repr for your class would be:

def __repr__(self):
    return f"{type(self).__name__}({self.name!r})"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading