ZetCode

Python __reduce_ex__ Method

Last modified November 18, 2026 Python 3.15

When an object is pickled, Python calls __reduce_ex__(protocol) rather than __reduce__, passing the protocol number in use. The method returns the tuple that tells pickle how to rebuild the object. This article shows which protocol values are passed, how to branch on them, how to return state and item iterators, how to rebuild live resources, how to use a custom reconstructor, and how copy reuses the same hook.

The protocol argument

Pickle passes the requested protocol number to __reduce_ex__. The hook below prints the number and returns a minimal two-element tuple.

protocol_argument.py
import pickle


class Probe:
    def __reduce_ex__(self, protocol):
        print("reduce_ex protocol:", protocol)
        return (self.__class__, ())


for proto in (0, 2, 4, 5):
    pickle.dumps(Probe(), protocol=proto)

The printed values match the protocols requested in the loop. Python 3.15 supports protocols 0 through 5, and the number reaches the hook unchanged so the reduction can be tailored to it.

$ python protocol_argument.py
reduce_ex protocol: 0
reduce_ex protocol: 2
reduce_ex protocol: 4
reduce_ex protocol: 5

__reduce_ex__ takes precedence

When both hooks are defined, __reduce_ex__ is the one pickle calls. The default implementation in object normally delegates to __reduce__, but an override replaces that behaviour.

precedence.py
import pickle


class Both:
    def __reduce__(self):
        print("__reduce__ called")
        return (self.__class__, ())

    def __reduce_ex__(self, protocol):
        print("__reduce_ex__ called", protocol)
        return (self.__class__, ())


pickle.dumps(Both(), protocol=4)

Only __reduce_ex__ ran. This is why a class that needs protocol-specific behaviour should override it rather than __reduce__.

$ python precedence.py
__reduce_ex__ called 4

Protocol-aware state

A three-element tuple adds state that is applied after reconstruction. Branching on the protocol lets older formats use a simpler representation. The constructor argument must remain valid for the reduced call, so data is optional here.

state_reduce_ex.py
import pickle


class CustomObject:
    def __init__(self, name, data=None):
        self.name = name
        self.data = data

    def __reduce_ex__(self, protocol):
        if protocol >= 2:
            return (self.__class__, (self.name,), {"data": self.data})
        return (self.__class__, (self.name, self.data))


obj = CustomObject("test", [1, 2, 3])
restored = pickle.loads(pickle.dumps(obj, protocol=4))
print(restored.name, restored.data)

For protocol 4 the three-element form was used: pickle called CustomObject("test") and then updated the new instance's dictionary with the data key. Defining __setstate__ would give full control over that step.

$ python state_reduce_ex.py
test [1, 2, 3]

Streaming items with listitems

Protocols 4 and 5 support a fourth tuple element: an iterator whose values are appended to the rebuilt object. This avoids putting a large collection inside the tuple itself, but the object must provide append().

listitems.py
import pickle


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

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

    def __reduce_ex__(self, protocol):
        if protocol >= 4:
            return (self.__class__, (), None, iter(self.items))
        return (self.__class__, (self.items,))


obj = Optimized(1, 2, 3)
restored = pickle.loads(pickle.dumps(obj, protocol=4))
print(restored.items)

The constructor was called with no arguments and each stored value was fed through append(). Without that method, unpickling would fail with an AttributeError.

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

Rebuilding external resources

Live objects such as connections should not be written into a pickle. A class can serialize only the recipe for recreating them, so unpickling calls the constructor and establishes the resource again.

resource.py
import pickle


class DatabaseConnection:
    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_ex__(self, protocol):
        return (self.__class__, (self.dsn,))


conn = DatabaseConnection("db://local")
restored = pickle.loads(pickle.dumps(conn))
print(restored.connection)

The connection was created for the original object and again during unpickling. Only the DSN string was serialized; the live connection object never entered the pickle stream.

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

A custom reconstruction function

The first tuple element does not have to be the class. Any callable works, which allows reconstruction that bypasses __init__ entirely.

reconstructor.py
import pickle


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

    def _calculate(self):
        self.sum = self.x + self.y

    def __reduce_ex__(self, protocol):
        return (reconstruct, (self.x, self.y))


def reconstruct(x, y):
    obj = ComplexObject.__new__(ComplexObject)
    obj.x = x
    obj.y = y
    obj._calculate()
    return obj


obj = ComplexObject(10, 20)
restored = pickle.loads(pickle.dumps(obj))
print(restored.sum)

The standalone function allocated the object with __new__, restored the fields and recomputed the derived value. This gives complete control, at the cost of more code to maintain.

$ python reconstructor.py
30

Pickling without an override

A class that defines no reduction hook inherits object.__reduce_ex__, which returns a tuple beginning with the internal __newobj__ helper. The copy module uses the same protocol, so the hook governs copying as well.

default_and_copy.py
import copy
import pickle


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


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

    def __reduce_ex__(self, protocol):
        print("custom reduce_ex", protocol)
        return (self.__class__, (self.value,))


print("default callable:", Plain(9).__reduce_ex__(4)[0].__name__)
print("pickle:", pickle.loads(pickle.dumps(Plain(9))).value)
print("copy:", copy.copy(Custom(7)).value)

The default reduction begins with __newobj__. The custom class printed its protocol when copy.copy() was called, confirming that copying shares the reduction machinery with pickling.

$ python default_and_copy.py
default callable: __newobj__
pickle: 9
custom reduce_ex 4
copy: 7

Best practices

A few rules keep __reduce_ex__ predictable:

Source

object.__reduce_ex__ - Python documentation

Pickle protocols - Python documentation

Pickling class instances - Python documentation

copy - Python documentation

In this article we have implemented the __reduce_ex__ method. We have covered the protocol argument, precedence over __reduce__, state, listitems streaming, live resources, custom reconstructors and copying. For related topics, see Python __reduce__ 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.