__repr__ vs. __str__ in Python
Key Differences Between __repr__ and __str__
Introduction
In Python, __repr__ and __str__ are two special methods used to define string representations of objects. While both methods aim to return a string version of an object, they serve different purposes and are used in different contexts. Understanding the distinction between __repr__ and __str__ is essential for writing clear and maintainable code, especially when working with custom classes.
Hi, my name is CyCoderX and in this article, we’ll explore the differences between __repr__ and __str__. Together we will examine their use cases, and provide practical examples to illustrate how to implement these methods effectively in your Python classes.
Let’s get crackin!
Did you know that you can clap up to 50 times ? Well now you do! Please consider helping me out by clapping and following me! 😊
Understanding __repr__ in Python
The __repr__ method in Python is intended to provide a string representation of an object that is as unambiguous as possible. The goal of __repr__ is to return a string that would allow someone to recreate the object using Python’s eval() function. If that’s not feasible, __repr__ should return a detailed, developer-oriented string representation of the object.
Key Characteristics of __repr__:
- Developer-Focused: The output of
__repr__is aimed at developers and should contain detailed information about the object. - Unambiguous: The string returned by
__repr__should be unambiguous and, ideally, executable. - Default Behavior: If you don’t explicitly define
__repr__in your class, Python will provide a default implementation that returns a string in the format<ClassName object at memory_address>.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
point = Point(2, 3)
print(repr(point)) # Output: Point(2, 3)In this example, the __repr__ method is defined to return a string that looks like the code you would write to create the object, making it easier for a developer to understand the object’s structure and values.
Understanding __str__ in Python
The __str__ method in Python is designed to provide a “pretty” or user-friendly string representation of an object. Unlike __repr__, which is aimed at developers, the __str__ method is meant for end-users. The output of __str__ is typically more readable and less detailed than __repr__, focusing on what makes sense to present to the user.
Get CyCoderX’s stories in your inbox
Join Medium for free to get updates from this writer.
Key Characteristics of __str__:
- User-Focused: The output of
__str__is intended to be easily understood by the user, often omitting technical details that are not necessary for understanding the object’s state. - Readable: The string returned by
__str__should be clean, concise, and easy to read. - Default Behavior: If
__str__is not defined in a class, Python will fall back on the__repr__method. If__repr__is also not defined, Python’s default implementation will be used.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"Point at coordinates ({self.x}, {self.y})"
point = Point(2, 3)
print(str(point)) # Output: Point at coordinates (2, 3)In this example, the __str__ method is defined to return a more readable description of the Point object, suitable for displaying to an end-user.
Key Differences Between __repr__ and __str__
Although __repr__ and __str__ might seem similar, they have distinct purposes and behaviors. Here are the key differences:
Purpose
__repr__: The primary purpose is to provide a detailed, unambiguous string representation of the object, which is useful for debugging and development.__str__: The primary purpose is to provide a readable, user-friendly string representation of the object, which is suitable for display to end-users.
Output Representation
__repr__: The output should ideally be a valid Python expression that could be used to recreate the object. It’s focused on providing enough detail to be useful for developers.__str__: The output is intended to be more human-readable and may omit technical details. It’s focused on providing a clear and concise description for users.
When to Use Each
__repr__: Use when you need a precise and detailed representation of the object, particularly in logging, debugging, or when working with other developers.__str__: Use when you need a more readable and user-friendly description of the object, particularly when displaying information to end-users.
Practical Examples of __repr__ and __str__
To better understand how __repr__ and __str__ are used in practice, let’s look at a few examples that demonstrate their different purposes and outputs.
Example 1: Custom Object Representation
Consider a class representing a simple 2D point. We’ll define both __repr__ and __str__ methods to see how they differ when printing the object.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"Point located at ({self.x}, {self.y})"
point = Point(5, 7)
# Using repr()
print(repr(point)) # Output: Point(5, 7)
# Using str()
print(str(point)) # Output: Point located at (5, 7)In this example, repr(point) returns a string that represents the object in a way that could be used to recreate it. On the other hand, str(point) returns a more descriptive and user-friendly message.
Example 2: Logging and Debugging
When debugging, you often need detailed information about the objects in your program. This is where __repr__ shines.
class Transaction:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __repr__(self):
return f"Transaction(amount={self.amount}, currency='{self.currency}')"
def __str__(self):
return f"{self.amount} {self.currency}"
transaction = Transaction(100, 'USD')
# Using repr() for logging
print(f"DEBUG: {repr(transaction)}") # Output: DEBUG: Transaction(amount=100, currency='USD')
# Using str() for displaying to the user
print(transaction) # Output: 100 USDHere, __repr__ is used to log a detailed representation of the Transaction object, which is helpful for debugging. __str__, however, provides a concise and readable format intended for the user.
Best Practices for Implementing __repr__ and __str__
To make the most of __repr__ and __str__ in your Python classes, consider these best practices:
1. Always Implement __repr__
- Even if you don’t plan to use
__str__, it’s good practice to implement__repr__for every class. A well-implemented__repr__can be invaluable for debugging and logging.
2. Make __repr__ Unambiguous
- Ensure that the string returned by
__repr__is unambiguous. If possible, it should return a string that could be passed toeval()to recreate the object.
3. Make __str__ Readable
- The string returned by
__str__should be easy to read and understand. Focus on clarity and conciseness, as this is the string that users will typically see.
4. Use F-Strings for Readability
- When implementing these methods, consider using Python’s f-strings for clarity and readability, especially when inserting variables into your strings.
5. Consider Your Audience
- Remember that
__repr__is for developers and__str__is for users. Tailor the content of these methods to their intended audience.
By following these best practices, you can ensure that your objects are represented clearly and appropriately in all contexts.
Conclusion
Understanding the differences between __repr__ and __str__ in Python is crucial for creating well-defined and user-friendly classes. While both methods are used to provide string representations of objects, they serve distinct purposes: __repr__ is designed for developers and should offer an unambiguous and detailed representation, while __str__ is meant for end-users and should be readable and concise.
By implementing both __repr__ and __str__ thoughtfully in your classes, you can make your objects more intuitive and easier to work with, whether for debugging, logging, or displaying information to users. The practical examples provided illustrate how these methods can be applied in real-world scenarios, helping you to create better Python code.
Remember, __repr__ is your go-to for an informative, developer-centric output, whereas __str__ is for user-facing content that needs to be clear and accessible. Both are powerful tools that, when used correctly, significantly enhance the usability and maintainability of your code.
Thank you for reading, and happy coding!
Final Words:
Thank you for taking the time to read my article!
This article was first published on medium by CyCoderX.
Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!
Join me as we explore the exciting world of AI, tech, data, and beyond!
What did you think about this article? Let me know in the comments below … or above, depending on your device 🙃
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: CoFeed | Differ
- More content at PlainEnglish.io









