[Python] How to effectively use `repr()` vs `str()` for debugging and object representation in...

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm learning more about Python's built-in functions and have come across repr(). I understand it's used to get a 'representation' of an object, but I'm a bit unclear on its practical use cases and how it differs from str().

    Specifically, I'm looking for explanations and examples on:

    1. Core Purpose: What is the primary intent or philosophy behind repr()? When would a developer typically use it?
    2. Basic Data Types: How does repr() behave with common Python data types like strings, integers, lists, and dictionaries?
    3. Custom Classes and __repr__: How do I implement the __repr__ special method in my own Python classes to control how my objects are represented?
    4. repr() vs. str(): What are the key distinctions between repr() and str()? When should I prefer one over the other for debugging, logging, or user-facing output?

    Any clear examples that illustrate these points would be extremely helpful! Thanks in advance.


    • What I tried:

      my_string = "hello"
      print(repr(my_string))

      my_list = [1, 2, 'three']
      print(repr(my_list))

      my_int = 123
      print(repr(my_int))

    • What I expected: For strings, I expected to see just hello (like print()). For lists and integers, I expected to see [1, 2, 'three'] and 123 respectively.


    • What actually resulted (Output):

      'hello'
      [1, 2, 'three']
      123

    The string output ('hello') with quotes was a bit unexpected, as was the identical output for lists and integers compared to standard print(). This made me realize repr() isn't simply for printing, and there's a difference between it and str() or implicit printing. I'm looking to understand the significance of this difference and how to apply repr() effectively, especially with custom classes.

    Continue reading...

Compartilhe esta Página