What use is '__reduce__'?

Peter Otten __peter__ at web.de
Fri Jan 8 15:12:18 EST 2016


Ian Kelly wrote:

> As you found by searching, __reduce__ is used to determine how
> instances of the class are pickled. If the example you're using
> doesn't do any pickling, then it's not really relevant to the example.
> It's probably included so that it won't be missed when the code is
> copied.

__reduce__() also makes copying work as expected:

>>> class OrderedCounter(Counter, OrderedDict):
...      'Counter that remembers the order elements are first seen'
...      def __repr__(self):
...          return '%s(%r)' % (self.__class__.__name__,
...                             OrderedDict(self))
...      def __reduce__(self):
...          return self.__class__, (OrderedDict(self),)
... 
>>> oc = OrderedCounter('abracadabra') 
>>> import copy
>>> copy.copy(oc)
OrderedCounter(OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 
1)]))

Now take away the __reduce__ method:

>>> del OrderedCounter.__reduce__
>>> copy.copy(oc)
OrderedCounter(OrderedDict([('b', 2), ('a', 5), ('c', 1), ('r', 2), ('d', 
1)]))





More information about the Python-list mailing list