Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #101396
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: What use is '__reduce__'? |
| Date | 2016-01-08 21:12 +0100 |
| Organization | None |
| Message-ID | <mailman.79.1452283950.2305.python-list@python.org> (permalink) |
| References | <399e214a-552b-4d4a-a39f-8e917dadd6c6@googlegroups.com> <CALwzidk-R-VVVi+59hRODxceb_rBr5WS=v+p8hOyLR1sZNPP8A@mail.gmail.com> |
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)]))
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
What use is '__reduce__'? Robert <rxjwg98@gmail.com> - 2016-01-08 08:42 -0800
Re: What use is '__reduce__'? Ian Kelly <ian.g.kelly@gmail.com> - 2016-01-08 10:03 -0700
Re: What use is '__reduce__'? Robert <rxjwg98@gmail.com> - 2016-01-08 09:45 -0800
Re: What use is '__reduce__'? Peter Otten <__peter__@web.de> - 2016-01-08 21:12 +0100
csiph-web