repr()

The built-in repr() function provides a developer-friendly string representation of an object. This string aims to be unambiguous and, ideally, should be able to recreate the object using the representation as an argument to the eval() function:

Python
>>> repr(42)
'42'
>>> repr([1, 2, 3])
'[1, 2, 3]'

repr() Signature

Python Syntax
repr(object)

Arguments

Argument Description
object The object to represent

Return Value

  • Returns a string that is a developer-friendly representation of the input object.

repr() Examples

With a simple integer as an argument:

Python
>>> repr(42)
'42'

With a list as an argument:

Python
>>> repr([1, 2, 3])
'[1, 2, 3]'

repr() Common Use Cases

The most common use cases for the repr() function include:

  • Debugging, to understand the structure and value of objects.
  • Logging, to capture a more precise state of objects.
  • Developing custom classes with clear, recreatable string representations.

repr() Real-World Example

Suppose you are developing a custom class to represent a Person. You want to provide a clear, developer-friendly representation of each instance:

Python person.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

# Usage
john = Person("John Doe", 35)
print(repr(john))  # Output: Person(name='John Doe', age=35)

In this example, repr() provides a clear and detailed representation of the Person object, which can be used to recreate the object.

repr() in Custom Classes

To support repr() in your custom classes, you can define the .__repr__() special method. Here’s how you can implement it:

Python book.py
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __repr__(self):
        class_name = type(self).__name__
        return f"{class_name}(title={self.title!r}, author={self.author!r})"

# Usage
odyssey = Book("The Odyssey", "Homer")
print(repr(odyssey))  # Output: Book(title='The Odyssey', author='Homer')

The .__repr__() method allows instances of the Book class to provide a detailed and developer-friendly string representation, which is useful for debugging and logging.

Tutorial

When Should You Use .__repr__() vs .__str__() in Python?

In this tutorial, you'll learn the difference between the string representations returned by .__repr__() vs .__str__() and understand how to use them effectively in classes that you define.

intermediate best-practices

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 14, 2024 • Reviewed by Dan Bader