Python repr() - Generate String Representation

Updated on November 22, 2024
repr() header image

Introduction

The repr() function in Python is designed to generate a string representation of an object that, ideally, can be used to recreate the object with eval(). This function is particularly valuable for developers who need to print concise, informative representations for debugging or logging purposes.

In this article, you will learn how to properly use the repr() function to create effective and readable string representations. Delve into its applications across various data types and learn the difference between repr() and its counterpart, str(), by exploring practical examples that highlight its usefulness in development.

Understanding repr() Basics

The Purpose of repr()

  1. Recognize that repr() is used to generate a string that, when passed to eval(), should ideally recreate the original object.
  2. Understand that repr() aims to generate an unambiguous representation of an object, as opposed to str() which is meant to be human-readable.

Comparing repr() and str()

  1. Note the primary difference: repr() is for developers, str() is for end-users.
  2. Realize how eval(repr(object)) should ideally reconstruct the original object, whereas str() does not carry this expectation.

Using repr() in Your Code

Generate String Representations of Basic Data Types

  1. Apply repr() to various data types and observe the output:

    python
    print(repr(1234))
    print(repr(123.45))
    print(repr("Hello, world!"))
    print(repr([1, 2, 3, 4, 5]))
    

    This snippet shows repr() applied to integers, floats, strings, and lists. Each outcome provides a detailed and accurate representation that could help in reconstructing the original object.

Custom Object Representations with repr()

  1. Use repr() with a custom class by defining a __repr__() method:

    python
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __repr__(self):
            return f"Person('{self.name}', {self.age})"
    
    person = Person("Alice", 30)
    print(repr(person))
    

    This code defines a Person class and a custom __repr__() method. The output from repr(person) is "Person('Alice', 30)", which is a clear, concise, and executable string representation.

Using repr() with Containers

  1. Create lists or dictionaries containing custom objects and apply repr():

    python
    people = [Person("Alice", 30), Person("Bob", 25)]
    print(repr(people))
    

    The output will retain the structure of the list with the repr() representation of its contents, providing a clear depiction of the container's structure and contents.

Conclusion

The repr() function in Python offers an indispensable tool for developers aiming to create precise and evaluable string representations of objects. By differing from str() in its intended audience and purpose, repr() serves as a cornerstone function for debugging and object inspection. Leveraging this function in your Python projects, especially when dealing with custom objects and complex data structures, enhances your code's clarity and maintainability. Always ensure to define a proper __repr__() method for custom classes to optimize debugging and logging practices.