13.4. Pickle Load

  • pickle.loads(bytes) -> object

  • pickle.load(file) -> object

13.4.1. SetUp

>>> import pickle

13.4.2. Sequence

>>> DATA = (
...     b'\x80\x04'
...     b'\x95\x17'
...     b'\x00\x00\x00\x00\x00\x00\x00'
...     b'\x8c\x05Alice\x94'
...     b'\x8c\x07Apricot\x94'
...     b'K\x1e\x87\x94'
...     b'.'
... )
>>>
>>> pickle.loads(DATA)
('Alice', 'Apricot', 30)

13.4.3. List of Sequences

>>> DATA = (
...     b'\x80\x04'
...     b'\x95\xa5'
...     b'\x00\x00\x00\x00\x00\x00\x00'
...     b']\x94('
...     b'\x8c\tfirstname\x94\x8c\x08lastname\x94\x8c\x03age\x94\x87\x94'
...     b'\x8c\x05Alice\x94\x8c\x07Apricot\x94K\x1e\x87\x94'
...     b'\x8c\x03Bob\x94\x8c\nBlackthorn\x94K\x1f\x87\x94'
...     b'\x8c\x05Carol\x94\x8c\x04Corn\x94K \x87\x94'
...     b'\x8c\x04Dave\x94\x8c\x06Durian\x94K!\x87\x94'
...     b'\x8c\x03Eve\x94\x8c\nElderberry\x94K"\x87\x94'
...     b'\x8c\x07Mallory\x94\x8c\x05Melon\x94K\x0f\x87\x94'
...     b'e.'
... )
>>>
>>> pickle.loads(DATA)
[('firstname', 'lastname', 'age'),
 ('Alice', 'Apricot', 30),
 ('Bob', 'Blackthorn', 31),
 ('Carol', 'Corn', 32),
 ('Dave', 'Durian', 33),
 ('Eve', 'Elderberry', 34),
 ('Mallory', 'Melon', 15)]

13.4.4. Mapping

>>> DATA = (
...     b'\x80\x04'
...     b'\x956'
...     b'\x00\x00\x00\x00\x00\x00\x00'
...     b'}\x94('
...     b'\x8c\tfirstname\x94\x8c\x05Alice\x94'
...     b'\x8c\x08lastname\x94\x8c\x07Apricot\x94'
...     b'\x8c\x03age\x94K\x1e'
...     b'u.'
... )
>>>
>>> pickle.loads(DATA)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}

13.4.5. List of Mappings

>>> DATA = (
...     b'\x80\x04'
...     b'\x95\xcd'
...     b'\x00\x00\x00\x00\x00\x00\x00'
...     b']\x94(}\x94('
...     b'\x8c\tfirstname\x94\x8c\x05Alice\x94'
...     b'\x8c\x08lastname\x94\x8c\x07Apricot\x94'
...     b'\x8c\x03age\x94K\x1eu}\x94(h\x02'
...     b'\x8c\x03Bob\x94h\x04\x8c\nBlackthorn\x94h\x06K\x1fu}\x94(h\x02'
...     b'\x8c\x05Carol\x94h\x04\x8c\x04Corn\x94h\x06K u}\x94(h\x02'
...     b'\x8c\x04Dave\x94h\x04\x8c\x06Durian\x94h\x06K!u}\x94(h\x02'
...     b'\x8c\x03Eve\x94h\x04\x8c\nElderberry\x94h\x06K"u}\x94(h\x02'
...     b'\x8c\x07Mallory\x94h\x04\x8c\x05Melon\x94h\x06K\x0f'
...     b'ue.'
... )
>>>
>>> pickle.loads(DATA)
[{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
 {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
 {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
 {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
 {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
 {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15}]

13.4.6. List of Objects

>>> DATA = (
...     b'\x80\x04'
...     b'\x95\x03\x01'
...     b'\x00\x00\x00\x00\x00\x00'
...     b']\x94('
...     b'\x8c\x08__main__\x94\x8c\x04User\x94\x93\x94)\x81\x94}\x94('
...     b'\x8c\tfirstname\x94\x8c\x05Alice\x94\x8c\x08lastname\x94\x8c\x07Apricot\x94\x8c\x03age\x94K\x1eubh\x03)\x81\x94}\x94(h\x06'
...     b'\x8c\x03Bob\x94h\x08\x8c\nBlackthorn\x94h\nK\x1fubh\x03)\x81\x94}\x94(h\x06'
...     b'\x8c\x05Carol\x94h\x08\x8c\x04Corn\x94h\nK ubh\x03)\x81\x94}\x94(h\x06'
...     b'\x8c\x04Dave\x94h\x08\x8c\x06Durian\x94h\nK!ubh\x03)\x81\x94}\x94(h\x06'
...     b'\x8c\x03Eve\x94h\x08\x8c\nElderberry\x94h\nK"ubh\x03)\x81\x94}\x94(h\x06'
...     b'\x8c\x07Mallory\x94h\x08\x8c\x05Melon\x94h\nK\x0f'
...     b'ube.'
... )
>>>
>>> class User:
...     def __init__(self, firstname, lastname, age):
...         self.firstname = firstname
...         self.lastname = lastname
...         self.age = age
...
...     def __repr__(self):
...         clsname = self.__class__.__name__
...         firstname = self.firstname
...         lastname = self.lastname
...         age = self.age
...         return f'{clsname}({firstname=}, {lastname=}, {age=})'
>>>
>>>
>>> pickle.loads(DATA)
[User(firstname='Alice', lastname='Apricot', age=30),
 User(firstname='Bob', lastname='Blackthorn', age=31),
 User(firstname='Carol', lastname='Corn', age=32),
 User(firstname='Dave', lastname='Durian', age=33),
 User(firstname='Eve', lastname='Elderberry', age=34),
 User(firstname='Mallory', lastname='Melon', age=15)]

13.4.7. From File

SetUp:

>>> DATA = (
...     b'\x80\x04\x95\x17\x00\x00\x00\x00\x00\x00\x00\x8c'
...     b'\x05Alice\x94\x8c\x07Apricot\x94K\x1e\x87\x94.'
... )
>>>
>>> with open('/tmp/myfile.txt', mode='wb') as file:
...     file.write(DATA)
34

Solution:

>>> with open('/tmp/myfile.txt', mode='rb') as file:
...     result = pickle.loads(DATA)
>>>
>>> print(result)
('Alice', 'Apricot', 30)

13.4.8. Recap

  • pickle.loads(bytes) -> object

  • pickle.load(file) -> object

  • open(file, mode='rb') for writing binary data

13.4.9. Assignments

# %% About
# - Name: Pickle Load Tuple
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% 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. Define `result: tuple` with deserialized data from `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: tuple` z zdeserializowanymi danymi z `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# ('Alice', 'Apricot', 30)

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

>>> assert type(result) is tuple, \
'Variable `result` has invalid type, should be tuple'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
('Alice', 'Apricot', 30)
"""

# %% 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
import pickle

# %% Types
result: tuple[str,str,int]

# %% Data
DATA = (
    b'\x80\x04'
    b'\x95\x17'
    b'\x00\x00\x00\x00\x00\x00\x00'
    b'\x8c\x05Alice\x94'
    b'\x8c\x07Apricot\x94'
    b'K\x1e\x87\x94'
    b'.'
)

# %% Result
result = ...

# %% About
# - Name: Pickle Load ListTuple
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% 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. Define `result: list[tuple]` with deserialized data from `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: list[tuple]` z zdeserializowanymi danymi z `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# [('firstname', 'lastname', 'age'),
#  ('Alice', 'Apricot', 30),
#  ('Bob', 'Blackthorn', 31),
#  ('Carol', 'Corn', 32),
#  ('Dave', 'Durian', 33),
#  ('Eve', 'Elderberry', 34),
#  ('Mallory', 'Melon', 15)]

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

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(row) is tuple for row in result), \
'Variable `result` has invalid type, should be tuple'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[('firstname', 'lastname', 'age'),
 ('Alice', 'Apricot', 30),
 ('Bob', 'Blackthorn', 31),
 ('Carol', 'Corn', 32),
 ('Dave', 'Durian', 33),
 ('Eve', 'Elderberry', 34),
 ('Mallory', 'Melon', 15)]
"""

# %% 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
import pickle

# %% Types
type header = tuple[str,str,str]
type row = tuple[str,str,int]
result: list[header|row]

# %% Data
DATA = (
    b'\x80\x04'
    b'\x95\xa5'
    b'\x00\x00\x00\x00\x00\x00\x00'
    b']\x94('
    b'\x8c\tfirstname\x94\x8c\x08lastname\x94\x8c\x03age\x94\x87\x94'
    b'\x8c\x05Alice\x94\x8c\x07Apricot\x94K\x1e\x87\x94'
    b'\x8c\x03Bob\x94\x8c\nBlackthorn\x94K\x1f\x87\x94'
    b'\x8c\x05Carol\x94\x8c\x04Corn\x94K \x87\x94'
    b'\x8c\x04Dave\x94\x8c\x06Durian\x94K!\x87\x94'
    b'\x8c\x03Eve\x94\x8c\nElderberry\x94K"\x87\x94'
    b'\x8c\x07Mallory\x94\x8c\x05Melon\x94K\x0f\x87\x94'
    b'e.'
)

# %% Result
result = ...

# %% About
# - Name: Pickle Load Dict
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% 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. Define `result: dict` with deserialized data from `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: dict` z zdeserializowanymi danymi z `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}

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

>>> assert type(result) is dict, \
'Variable `result` has invalid type, should be dict'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
"""

# %% 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
import pickle

# %% Types
result: dict[str,str|int]

# %% Data
DATA = (
    b'\x80\x04'
    b'\x956'
    b'\x00\x00\x00\x00\x00\x00\x00'
    b'}\x94('
    b'\x8c\tfirstname\x94\x8c\x05Alice\x94'
    b'\x8c\x08lastname\x94\x8c\x07Apricot\x94'
    b'\x8c\x03age\x94K\x1e'
    b'u.'
)

# %% Result
result = ...

# %% About
# - Name: Pickle Load ListDict
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% 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. Define `result: list[dict]` with deserialized data from `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: list[dict]` z zdeserializowanymi danymi z `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
#  {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
#  {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
#  {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
#  {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
#  {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15}]

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

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(row) is dict for row in result), \
'Variable `result` has invalid type, should be dict'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
 {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
 {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
 {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
 {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
 {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15}]
"""

# %% 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
import pickle

# %% Types
type row = dict[str,str|int]
result: list[row]

# %% Data
DATA = (
    b'\x80\x04'
    b'\x95\xcd'
    b'\x00\x00\x00\x00\x00\x00\x00'
    b']\x94(}\x94('
    b'\x8c\tfirstname\x94\x8c\x05Alice\x94'
    b'\x8c\x08lastname\x94\x8c\x07Apricot\x94'
    b'\x8c\x03age\x94K\x1eu}\x94(h\x02'
    b'\x8c\x03Bob\x94h\x04\x8c\nBlackthorn\x94h\x06K\x1fu}\x94(h\x02'
    b'\x8c\x05Carol\x94h\x04\x8c\x04Corn\x94h\x06K u}\x94(h\x02'
    b'\x8c\x04Dave\x94h\x04\x8c\x06Durian\x94h\x06K!u}\x94(h\x02'
    b'\x8c\x03Eve\x94h\x04\x8c\nElderberry\x94h\x06K"u}\x94(h\x02'
    b'\x8c\x07Mallory\x94h\x04\x8c\x05Melon\x94h\x06K\x0f'
    b'ue.'
)

# %% Result
result = ...

# %% About
# - Name: Pickle Load ListObjects
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% 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. Define `result: list[object]` with deserialized data from `FILE`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: list[object]` z zdeserializowanymi danymi z `FILE`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# [User(firstname='Alice', lastname='Apricot', age=30),
#  User(firstname='Bob', lastname='Blackthorn', age=31),
#  User(firstname='Carol', lastname='Corn', age=32),
#  User(firstname='Dave', lastname='Durian', age=33),
#  User(firstname='Eve', lastname='Elderberry', age=34),
#  User(firstname='Mallory', lastname='Melon', age=15)]

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

>>> from os import remove
>>> remove(FILE)

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(row) is User for row in result), \
'Variable `result` has invalid type, should be User'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[User(firstname='Alice', lastname='Apricot', age=30),
 User(firstname='Bob', lastname='Blackthorn', age=31),
 User(firstname='Carol', lastname='Corn', age=32),
 User(firstname='Dave', lastname='Durian', age=33),
 User(firstname='Eve', lastname='Elderberry', age=34),
 User(firstname='Mallory', lastname='Melon', age=15)]
"""

# %% 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
import pickle

# %% Types
result: list[dict[str, str|int|None]]

# %% Data
FILE = r'_temporary.pkl'


class User:
    def __init__(self, firstname, lastname, age):
        self.firstname = firstname
        self.lastname = lastname
        self.age = age

    def __repr__(self):
        clsname = self.__class__.__name__
        firstname = self.firstname
        lastname = self.lastname
        age = self.age
        return f'{clsname}({firstname=}, {lastname=}, {age=})'


DATA = [
    User(firstname='Alice', lastname='Apricot', age=30),
    User(firstname='Bob', lastname='Blackthorn', age=31),
    User(firstname='Carol', lastname='Corn', age=32),
    User(firstname='Dave', lastname='Durian', age=33),
    User(firstname='Eve', lastname='Elderberry', age=34),
    User(firstname='Mallory', lastname='Melon', age=15),
]


with open(FILE, mode='wb') as file:
    pickle.dump(DATA, file)


# %% Result