Python Language String representations of class instances: __str__ and __repr__ methods

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


A note about implemeting both methods

When both methods are implemented, it's somewhat common to have a __str__ method that returns a human-friendly representation (e.g. "Ace of Spaces") and __repr__ return an eval-friendly representation.

In fact, the Python docs for repr() note exactly this:

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.

What that means is that __str__ might be implemented to return something like "Ace of Spaces" as shown previously, __repr__ might be implemented to instead return Card('Spades', 1)

This string could be passed directly back into eval in somewhat of a "round-trip":

object -> string -> object

An example of an implementation of such a method might be:

def __repr__(self):
    return "Card(%s, %d)" % (self.suit, self.pips)


[1] This output is implementation specific. The string displayed is from cpython.

[2] You may have already seen the result of this str()/repr() divide and not known it. When strings containing special characters such as backslashes are converted to strings via str() the backslashes appear as-is (they appear once). When they're converted to strings via repr() (for example, as elements of a list being displayed), the backslashes are escaped and thus appear twice.

Got any Python Language Question?