Python repr() built-in function

From the Python 3 documentation

Return a string containing a printable representation of an object. 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. A class can control what this function returns for its instances by defining a __repr__() method.

Introduction

The repr() function returns a string containing a printable representation of an object. The goal of repr() is to be unambiguous. For many types, repr() returns a string that can be executed by eval() to create an identical object.

This is different from str(), which is intended to be human-readable.

Example

import datetime

# For a string, repr() adds quotes
print(repr("hello"))  # Output: "'hello'"

# For a datetime object, it's unambiguous
now = datetime.datetime.now()
print(repr(now))  # Output: e.g., 'datetime.datetime(2023, 10, 27, 10, 0, 0, 123456)'

# You can define __repr__ for your own classes
class Person:
    def __init__(self, name):
        self.name = name

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

p = Person("John")
print(repr(p))  # Output: "Person(name='John')"

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.