Enjoy The Loop Blog
Sign in

I had no idea __repr__ did this.

__repr__ should return an unambiguous developer-friendly representation of an object. Ideally, it can even recreate the object.

__str__ displays the object in a friendlier way.

Example:

__repr__ -> DirItem("notes.txt")
__str__  -> notes.txt

I seldom override repr and str.

And when I do, it is usually for quick debugging sessions. I never use them to display values in a website or macOS app. That is not what they are for.

You probably already know what __str__ does. It transforms output from this:

<__main__.DirItem object at 0x100c046e0>

into this:

addresses.cfg

But then I printed a list of DirItem objects:

[<__main__.DirItem object at 0x100c046e0>,
 <__main__.DirItem object at 0x100bf0690>,
 <__main__.DirItem object at 0x100bf07d0>]

Damn. Those object addresses again.

So I always used this shortcut:

for di in diritems:
    print(di)
addresses.cfg
readme.md
system.txt

And last week, after 7 years of programming in Python, I learned that lists automatically use __repr__ for their items.

class DirItem:
    def __init__(self, name: str) -> None:
        self.name = name

    def __repr__(self) -> str:
        return f"DirItem('{self.name}')"

items = [
    DirItem("addresses.cfg"),
    DirItem("readme.md"),
    DirItem("system.txt")
]

print(items)

Output:

[DirItem('addresses.cfg'),
 DirItem('readme.md'),
 DirItem('system.txt')]

Written by Loek van den Ouweland on May 21, 2026.