DeployU
Interviews / Backend Engineering / What is the difference between `__str__` and `__repr__` in Python?

What is the difference between `__str__` and `__repr__` in Python?

conceptual Object-Oriented Programming Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are writing a new class to represent a financial transaction. You want to be able to print the object to the console for debugging purposes, and you also want to be able to display a user-friendly representation of the object to the user.

The Challenge

Explain the difference between the __str__ and __repr__ methods in Python. Which one would you use for each of these use cases, and why?

Wrong Approach

A junior engineer might not be aware of the difference between these two methods. They might just implement the `__str__` method and use it for both debugging and display purposes.

Right Approach

A senior engineer would know that `__str__` is for display purposes and `__repr__` is for debugging purposes. They would be able to explain the difference between the two methods and would have a clear plan for how to use them to solve this problem.

Step 1: Understand the Key Differences

MethodPurpose
__str__To return a user-friendly string representation of an object.
__repr__To return an unambiguous string representation of an object that can be used for debugging.

Step 2: Choose the Right Tool for the Job

For our use case, we would use:

  • __str__ to display a user-friendly representation of the transaction to the user.
  • __repr__ to print the transaction to the console for debugging purposes.

Step 3: Code Examples

Here is an example of how to implement these two methods in our Transaction class:

class Transaction:
    def __init__(self, amount, currency, description):
        self.amount = amount
        self.currency = currency
        self.description = description

    def __str__(self):
        return f"{self.amount} {self.currency} - {self.description}"

    def __repr__(self):
        return f"Transaction(amount={self.amount}, currency='{self.currency}', description='{self.description}')"

# Create a new transaction
tx = Transaction(100, "USD", "Dinner with friends")

# Print the transaction
print(tx) # 100 USD - Dinner with friends

# Get the representation of the transaction
repr(tx) # "Transaction(amount=100, currency='USD', description='Dinner with friends')"

A good rule of thumb is that eval(repr(obj)) == obj.

Practice Question

You are debugging a complex object and want to see a detailed representation of it. Which of the following would you use?