What is the purpose of `repr()`?

QuestionsQuestions8 SkillsProDec, 11 2025
0124

That's an excellent question, and it highlights a key difference when working with Python objects!

The purpose of repr() (short for "representation") is to return a string containing a printable, unambiguous, and often "developer-friendly" representation of an object.

Here's a breakdown of its characteristics and purpose:

  1. Unambiguous Representation: The goal of repr() is to produce a string that, if passed to eval(), would ideally recreate the original object (though this isn't always possible or desirable for all objects). It's meant to be technically accurate.
  2. Developer-Oriented: The output of repr() is typically more useful for developers or debugging. It often includes information about the object's type and its internal state.
  3. Default Implementation:
    • For many built-in types (like integers, strings, lists), repr() provides a literal representation:
      >>> repr(10)
      '10'
      >>> repr("hello")
      "'hello'" # Notice the quotes, showing it's a string literal
      >>> repr([1, 2, 3])
      '[1, 2, 3]'
    • For custom objects or more complex types (like the datetime object in our step), repr() often provides a string that shows how the object could be constructed.
      import datetime
      now = datetime.datetime(2023, 10, 27, 10, 30, 0)
      print(f"repr(now): {repr(now)}")
      # Output: repr(now): datetime.datetime(2023, 10, 27, 10, 30)
      As you can see, repr(now) tells you it's a datetime.datetime object and shows the arguments you'd use to create an identical one.

How does it differ from str()?

  • str() (which is what print() typically calls) aims for a readable and user-friendly representation.
  • repr() aims for an unambiguous and developer-friendly representation.

Think of it this way:

  • str() is for humans to read.
  • repr() is for Python (or other developers) to understand how to recreate or debug the object.

Does this explanation help clarify the role of repr() for you?

0 Comments

no data
Be the first to share your comment!