On Fri, Sep 18, 2020 at 10:42 PM Guido van Rossum email@example.com wrote:
At the same time it's as old as Python -- for most builtins other than strings, repr() and str() are the same, and modeled after repr(). Historically, I only introduced the difference between str() and repr() because of strings -- I wanted the REPL to clearly show the difference between the number 42 and the string '42', but at the same time I wanted both to print as just '42'. Of course numpy took a different fork in that road...
That's an interesting history tidbit, thanks for sharing, Guido. Like Ethan, I also find that distinction invaluable!
While researching the first edition of Fluent Python, I found the 1996 paper "How to Display an Object as a String: printString and displayString" . In it, the author Bobby Woolf explains that VisualWorks Smalltalk's `Object` class provides two methods:
""" • printString—Displays the object the way the developer wants to see it. • displayString—Displays the object the way the user wants to see it. """
I love these simple definitions, and they are followed by most Python classes that have distinct __repr__ and __str__.
Developers or users rarely care about the numeric value of an Enum, so I am for __repr__ providing a "more qualified name" and __str__ providing a "less qualified name", but still qualified with at least one dot in it—eg. Color.RED and not RED). In the rare cases where someone cares about the underlying integer, let them get the value.
-- Luciano Ramalho | Author of Fluent Python (O'Reilly, 2015) | http://shop.oreilly.com/product/0636920032519.do | Technical Principal at ThoughtWorks | Twitter: @ramalhoorg