repr() Function in Python

Python repr() Function

In Python, the repr() function is a built-in function that returns a string representation of an object. The name "repr" stands for "representation." The string returned by repr() is usually a valid Python expression that could be used to recreate the object it represents. It is often used for debugging and inspection purposes.

The basic syntax of the repr() function is as follows:

repr(object)

Here, object is the Python object for which you want to obtain the string representation. The repr() function then processes the object and returns a string representing its value.

For example:

num = 42
print(repr(num))  # Output: '42'

str_val = "Hello, World!"
print(repr(str_val))  # Output: "'Hello, World!'"

In the above examples, repr() returns the string representations of the num and str_val variables.

The main difference between repr() and str() functions is that repr() aims to create a representation that can be used to recreate the object, while str() is meant to create a human-readable representation of the object. Often, str() will produce more concise and user-friendly output, while repr() will give a more detailed and programmer-oriented representation.

For example:

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

person = Person("Alice", 30)
print(str(person))  # Output: '<__main__.Person object at 0x...>'
print(repr(person))  # Output: '<__main__.Person object at 0x...>'

In this example, str(person) and repr(person) produce similar output, but repr(person) includes more details like the object's class and memory address.

By default, if a class does not define its own __repr__() method, the repr() function will fall back to using the default implementation, which returns a string containing the object's type and memory address.

You can customize the string representation of your objects by defining the __repr__() method in your classes. By doing so, you can control what repr() returns for instances of your class.