17.8. OOP Stringification

  • str() - Dedicated for end-users (object stringification)

  • repr() - Dedicated for developers (object representation)

17.8.1. Problem

>>> class User:
...     def __init__(self, username, password):
...         self.username = username
...         self.password = password
>>>
>>>
>>> alice = User('alice', 'secret')
>>>
>>> print(alice)
<__main__.User object at 0x1087b12b0>

What's that?

>>> type(alice)
<class '__main__.User'>
>>>
>>> hex(id(alice))
'0x1087b12b0'

17.8.2. Str

  • Dedicated for end-users (object stringification)

  • Calling function print(obj) calls str(obj)

  • Calling function str(obj) calls obj.__str__()

  • Calling f'{obj}' calls obj.__str__()

  • Calling f'{obj!s}' calls obj.__str__()

  • Method obj.__str__() must return str

Object without __str__() method overloaded prints their memory address:

>>> class User:
...     def __init__(self, username, password):
...         self.username = username
...         self.password = password
>>>
>>>
>>> alice = User('alice', 'secret')
>>>
>>> print(alice)
<__main__.User object at 0x10aef7450>
>>>
>>> str(alice)
'<__main__.User object at 0x10aef7450>'
>>>
>>> alice.__str__()
'<__main__.User object at 0x10aef7450>'
>>>
>>> f'{alice}'
'<__main__.User object at 0x10aef7450>'
>>>
>>> f'{alice!s}'
'<__main__.User object at 0x10aef7450>'

Objects can verbose print if __str__() method is present:

>>> class User:
...     def __init__(self, username, password):
...         self.username = username
...         self.password = password
...
...     def __str__(self):
...         return self.username.capitalize()
...
>>> alice = User('alice', 'secret')
>>>
>>> print(alice)
Alice
>>>
>>> str(alice)
'Alice'
>>>
>>> alice.__str__()
'Alice'
>>>
>>> f'Hello {alice}'
'Hello Alice'
>>>
>>> f'Hello {alice!s}'
'Hello Alice'

17.8.3. Repr

  • Dedicated for developers (object representation)

  • 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

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

>>> class User:
...     def __init__(self, username, password):
...         self.username = username
...         self.password = password
...
...
>>> alice = User('alice', 'secret')
>>>
>>> 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>'

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

>>> class User:
...     def __init__(self, username, password):
...         self.username = username
...         self.password = password
...
...     def __repr__(self):
...         username = self.username
...         password = self.password
...         return f'User({username=}, {password=})'
...
...
>>> alice = User('alice', 'secret')
>>>
>>> alice
User(username='alice', password='secret')
>>>
>>> repr(alice)
"User(username='alice', password='secret')"
>>>
>>> alice.__repr__()
"User(username='alice', password='secret')"
>>>
>>> f'{alice!r}'
"User(username='alice', password='secret')"

17.8.4. Case Study

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

17.8.5. Use Case - 1

>>> from pprint import pprint

Problem:

>>> class User:
...     def __init__(self, username, password):
...         self.username = username
...         self.password = password
>>>
>>>
>>> alice = User('alice', 'secret')
>>> bob = User('bob', 'qwerty')
>>> carol = User('carol', '123456')
>>>
>>> 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, username, password):
...         self.username = username
...         self.password = password
...
...     def __str__(self):
...         return f'{self.username} {self.password}'
...
...     def __repr__(self):
...         cls = self.__class__.__name__
...         username = self.username
...         password = self.password
...         return f'{cls}({username=}, {password=})'
>>>
>>>
>>> alice = User('alice', 'secret')
>>> bob = User('bob', 'qwerty')
>>> carol = User('carol', '123456')
>>>
>>> result = []
>>> result.append(alice)
>>> result.append(bob)
>>> result.append(carol)
>>>
>>> pprint(result)
[User(username='alice', password='secret'),
 User(username='bob', password='qwerty'),
 User(username='carol', password='123456')]

17.8.6. Assignments

# %% About
# - Name: OOP Stringification Str
# - 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 `__str__` which returns users firstname and lastname
#    example: 'Alice Apricot'
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj klasę `User`
# 2. Zdefiniuj nową metodę `__str__`, która zwraca imię i nazwisko użytkownika
#    przykład: 'Alice Apricot'
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

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

>>> assert isclass(User)
>>> assert hasattr(User, '__init__')
>>> assert hasattr(User, '__str__')

>>> alice = User('Alice', 'Apricot')
>>> result = str(alice)
>>> pprint(result)
'Alice Apricot'
"""

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

# %% Imports

# %% Types

# %% Data

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

# %% 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ść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

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

>>> assert isclass(User)
>>> assert hasattr(User, '__init__')
>>> assert hasattr(User, '__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 -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