ZetCode

Python __reduce__ Method

Last modified November 18, 2026 Python 3.15

The pickle module calls __reduce__ to find out how to rebuild an object. The method returns a tuple describing a callable, its arguments, optional state and optional item iterators. This article covers a minimal round-trip, state restoration, recreating non-picklable attributes, validating data, the fourth and fifth tuple elements, and how copy reuses the same protocol.

A minimal reduction

The simplest tuple has two elements: a callable that recreates the object and the arguments to pass to it. Unpickling calls SimpleObject(42).

minimal_reduce.py
import pickle


class SimpleObject:
    def __init__(self, value):
        self.value = value

    def __reduce__(self):
        return (self.__class__, (self.value,))


obj = SimpleObject(42)
restored = pickle.loads(pickle.dumps(obj))
print(restored.value)
print(type(restored).__name__)

The value and the class both survived the round-trip. The class object is a suitable callable because calling it with the stored arguments reconstructs the instance.

$ python minimal_reduce.py
42
SimpleObject

Restoring extra state

A third tuple element is passed to __setstate__ after the object has been rebuilt. This is where attributes not supplied to the constructor are restored.

state_reduce.py
import pickle


class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __reduce__(self):
        return (self.__class__, (self.x, self.y), {"color": "red"})

    def __setstate__(self, state):
        self.color = state.get("color", "blue")

    def __repr__(self):
        return f"Point({self.x}, {self.y}, {self.color})"


p = pickle.loads(pickle.dumps(Point(3, 4)))
print(p)

The constructor received the coordinates and __setstate__ received the colour dictionary. Without a __setstate__ method, pickle would instead update the instance dictionary with the state.

$ python state_reduce.py
Point(3, 4, red)

Rebuilding non-picklable attributes

Live resources such as sockets or file handles cannot be pickled. A class can store only the recipe for rebuilding them and recreate the resource in __init__ when the object is loaded.

resource_reduce.py
import pickle


class Connection:
    def __init__(self, dsn):
        self.dsn = dsn
        self.connection = self._connect()

    def _connect(self):
        print("connecting to", self.dsn)
        return f"<connection:{self.dsn}>"

    def __reduce__(self):
        return (self.__class__, (self.dsn,))


original = Connection("db://local")
restored = pickle.loads(pickle.dumps(original))
print(restored.connection)

The connection was created once for the original object and again during unpickling. Only the DSN string was serialized, so the live resource is never written into the pickle stream.

$ python resource_reduce.py
connecting to db://local
connecting to db://local
<connection:db://local>

Validating the reconstruction data

Because a reduction tuple can name any callable, unpickling untrusted data is dangerous. A class can at least reject obviously bad data when it is being pickled, before the bytes leave the process.

validate_reduce.py
import pickle


class SafeData:
    def __init__(self, text):
        self.text = text

    def __reduce__(self):
        if any(ch in self.text for ch in ";&|"):
            raise ValueError("invalid characters in data")
        return (self.__class__, (self.text,))


safe = SafeData("ordinary text")
print(pickle.loads(pickle.dumps(safe)).text)
try:
    pickle.dumps(SafeData("value; malicious"))
except ValueError as e:
    print(type(e).__name__, e)

Valid input round-trips normally and suspicious input is rejected early. This check is only a small safeguard: never unpickle data from an untrusted source, because a malicious pickle can request arbitrary callables regardless of this class.

$ python validate_reduce.py
ordinary text
ValueError invalid characters in data

The listitems and dictitems elements

The fourth and fifth elements of the reduction tuple are iterators. Items from the fourth are appended with append(), and pairs from the fifth are inserted with __setitem__. This avoids embedding a large container in the tuple itself.

item_reduce.py
import pickle


class Bag:
    def __init__(self, *items):
        self.items = list(items)

    def append(self, item):
        self.items.append(item)

    def __reduce__(self):
        return (self.__class__, (), None, iter(self.items))


bag = pickle.loads(pickle.dumps(Bag(1, 2, 3), protocol=4))
print(bag.items)

The constructor was called with no arguments and each stored item was fed through append(). The object must provide that method when the fourth tuple element is used.

$ python item_reduce.py
[1, 2, 3]

A dictitems example

The fifth element works the same way for key-value pairs. The reconstructed object needs to support item assignment.

dictitems_reduce.py
import pickle


class DictBag:
    def __init__(self, **values):
        self.data = dict(values)

    def __setitem__(self, key, value):
        self.data[key] = value

    def __reduce__(self):
        return (self.__class__, (), None, None, iter(self.data.items()))


bag = pickle.loads(pickle.dumps(DictBag(a=1, b=2), protocol=4))
print(bag.data)

Each pair was inserted with __setitem__, preserving the mapping. The fourth element was set to None because this class does not need list items.

$ python dictitems_reduce.py
{'a': 1, 'b': 2}

Pickle protocols and copy

Python 3.15 supports protocols up to 5. If a class defines no __reduce__, object.__reduce_ex__ supplies a default. The copy module also uses the reduction protocol, so the same method governs copying and deep copying.

protocol_reduce.py
import copy
import pickle


class SimpleObject:
    def __init__(self, value):
        self.value = value

    def __reduce__(self):
        return (self.__class__, (self.value,))


obj = SimpleObject(7)
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
print("protocol:", pickle.HIGHEST_PROTOCOL)
print("round-trip:", pickle.loads(data).value)
print("copy:", copy.copy(obj).value)
print("deepcopy:", copy.deepcopy(obj).value)

The highest protocol is 5, and pickling, copying and deep copying all reconstructed the same value. Implementing __reduce__ therefore controls several operations at once.

$ python protocol_reduce.py
protocol: 5
round-trip: 7
copy: 7
deepcopy: 7

Best practices

A few rules keep __reduce__ predictable:

Source

object.__reduce__ - Python documentation

Pickling class instances - Python documentation

pickle - Python documentation

copy - Python documentation

In this article we have implemented the __reduce__ method. We have covered the reduction tuple, state restoration, live resources, validation, list and dict items, protocols and copy. For related topics, see Python __reduce_ex__ method, Python pickle module, and Python serialization.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.