Python repr()
Function
The repr() function returns a string representation of an object that can often be used to recreate the object. It's useful for debugging and logging because it gives more detail than just printing the value.
Syntax
repr(object)
Parameters:
object
– Any Python object you want to inspect.
Returns:
- A string that is a printable, and often evaluable, representation of the object.
Example 1: Using repr()
with Strings
text = "Hello
World"
print(text) # Output as interpreted by print
print(repr(text)) # Raw string representation
Hello
World
'Hello\nWorld'
Explanation: repr()
shows the escape characters like \n
instead of turning them into a newline. This helps you see the actual string content.
Example 2: Using repr()
with Numbers
num = 3.14159
print(repr(num))
3.14159
With numbers, repr()
behaves the same as str()
, but it's more accurate for floating point values.
Example 3: Custom Objects and __repr__()
class Person:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Person(name='{self.name}')"
p = Person("Alice")
print(p)
print(repr(p))
Person(name='Alice')
Person(name='Alice')
Explanation: You can define your own __repr__()
method to control how objects are displayed with repr()
.
Use Case: Debugging
When you're logging or printing complex data structures, repr()
helps you see the full raw format, which is better for developers to inspect values and structure.
repr() vs str()
Function | Purpose |
---|---|
str() | Returns a readable version (for end users). |
repr() | Returns an official, raw representation (for developers). |
Common Mistakes
- Using
repr()
for display whenstr()
is more readable for users. - Forgetting to define
__repr__()
in custom classes — making debugging harder.
Interview Tip
If asked how to get the “developer version” of an object’s string, say repr()
. It’s also used internally by the interpreter when displaying objects in the shell.
Summary
repr()
gives a detailed, unambiguous string representation of objects.- Ideal for debugging, logging, and understanding what's really inside an object.
- You can customize its behavior in classes using
__repr__()
.
Practice Problem
Create a class Book
with attributes title
and author
. Override __repr__()
to return something like: Book(title='...', author='...')
.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __repr__(self):
return f"Book(title='{self.title}', author='{self.author}')"
b = Book("1984", "George Orwell")
print(repr(b))