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.
repr()
is used to generate a string that, when passed to eval()
, should ideally recreate the original object.repr()
aims to generate an unambiguous representation of an object, as opposed to str()
which is meant to be human-readable.repr()
is for developers, str()
is for end-users.eval(repr(object))
should ideally reconstruct the original object, whereas str()
does not carry this expectation.Apply repr()
to various data types and observe the output:
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.
Use repr()
with a custom class by defining a __repr__()
method:
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.
Create lists or dictionaries containing custom objects and apply repr()
:
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.
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.