17.9. OOP Repr

  • repr(obj) - object representation

  • Dedicated for developers

  • Calling function repr(obj) calls obj.__repr__()

  • Method obj.__repr__() must return str

  • Copy-paste for creating object with the same values

  • Useful for debugging

  • Printing list will call __repr__() method on each element

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> alice = User('Alice', 'Apricot')
>>>
>>> alice
'<__main__.User object at 0x1087b12b0>'

17.9.1. Problem

  • Object without __repr__() method overloaded prints their memory address

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...
>>> alice = User('Alice', 'Apricot')
>>>
>>> alice
<__main__.User object at 0x10aef7450>
>>>
>>> repr(alice)
'<__main__.User object at 0x10aef7450>'
>>>
>>> alice.__repr__()
'<__main__.User object at 0x10aef7450>'
>>>
>>> f'{alice!r}'
'<__main__.User object at 0x10aef7450>'

17.9.2. Solution

  • Objects can verbose print if __repr__() method is present

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __repr__(self):
...         clsname = self.__class__.__name__
...         firstname = self.firstname
...         lastname = self.lastname
...         return f'{clsname}({firstname=}, {lastname=})'
>>>
>>>
>>> alice = User('Alice', 'Apricot')
>>>
>>> alice
User(firstname='Alice', lastname='Apricot')
>>>
>>> repr(alice)
"User(firstname='Alice', lastname='Apricot')"
>>>
>>> alice.__repr__()
"User(firstname='Alice', lastname='Apricot')"
>>>
>>> f'{alice!r}'
"User(firstname='Alice', lastname='Apricot')"

17.9.3. Case Study

>>> import datetime
>>>
>>> today = datetime.date(2000, 1, 2)
>>> str(today)
'2000-01-02'
>>> repr(today)
'datetime.date(2000, 1, 2)'

17.9.4. Use Case - 1

>>> class User:
...     def __init__(self, username, password):
...         self.username = username
...         self.password = password
...
...     def __str__(self):
...         return f'User {self.username}'
...
...     def __repr__(self):
...         clsname = self.__class__.__name__
...         username = self.username
...         password = '******'
...         return f'{clsname}({username=}, {password=})'
>>>
>>>
>>> alice = User('alice', 'secret')
>>>
>>> print(alice)
User alice
>>>
>>> alice
User(username='alice', password='******')

17.9.5. Use Case - 2

>>> from pprint import pprint

Problem:

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> alice = User('Alice', 'Apricot')
>>> bob = User('Bob', 'Blackthorn')
>>> carol = User('Carol', 'Corn')
>>>
>>> result = []
>>> result.append(alice)
>>> result.append(bob)
>>> result.append(carol)
>>>
>>> result
[<__main__.User at 0x10c37bf80>,
 <__main__.User at 0x10c3789e0>,
 <__main__.User at 0x10c37a990>]

Solution:

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __str__(self):
...         return f'{self.firstname} {self.lastname}'
...
...     def __repr__(self):
...         clsname = self.__class__.__name__
...         firstname = self.firstname
...         lastname = self.lastname
...         return f'{clsname}({firstname=}, {lastname=})'
>>>
>>>
>>> alice = User('Alice', 'Apricot')
>>> bob = User('Bob', 'Blackthorn')
>>> carol = User('Carol', 'Corn')
>>>
>>> result = []
>>> result.append(alice)
>>> result.append(bob)
>>> result.append(carol)
>>>
>>> pprint(result)
[User(firstname='Alice', lastname='Apricot'),
 User(firstname='Bob', lastname='Blackthorn'),
 User(firstname='Carol', lastname='Corn')]

17.9.6. Assignments

# %% About
# - Name: OOP Stringification Repr
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Modify class `User`
# 2. Define new method `__repr__` for displaying class name, fields and their values
#    example: "User(firstname='Alice', lastname='Apricot')"
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj klasę `User`
# 2. Zdefiniuj nową metodę `__repr__` do wyświetlania nazwy klasy, pól i ich wartości
#    przykład: "User(firstname='Alice', lastname='Apricot')"
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> alice = User('Alice', 'Apricot')
# >>> repr(alice)
# "User(firstname='Alice', lastname='Apricot')"

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> from pprint import pprint
>>> from inspect import isclass

>>> assert isclass(User), \
'Object `User` has an invalid type; expected: `class`.'

>>> assert hasattr(User, '__init__'), \
'Object `User` has an invalid attribute; expected: to have an attribute `__init__`.'

>>> assert hasattr(User, '__repr__'), \
'Object `User` has an invalid attribute; expected: to have an attribute `__repr__`.'

>>> alice = User('Alice', 'Apricot')
>>> result = repr(alice)
>>> pprint(result)
"User(firstname='Alice', lastname='Apricot')"
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
User: type
__repr__: Callable[[object], str]

# %% Data

# %% Result
class User:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname