Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: What use is '__reduce__'? Date: Fri, 08 Jan 2016 21:12:18 +0100 Organization: None Lines: 32 Message-ID: References: <399e214a-552b-4d4a-a39f-8e917dadd6c6@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de nXsXTS0j9dWnrIBmvMsx/Qen3A4DAN8PfLPzv11BAjPw== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; '5),': 0.09; 'method:': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.13; 'missed': 0.15; "'%s(%r)'": 0.16; "('b',": 0.16; "('c',": 0.16; "('r',": 0.16; '1),': 0.16; '2),': 0.16; 'copied.': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'remembers': 0.16; 'wrote:': 0.16; 'example.': 0.18; '>>>': 0.20; 'elements': 0.23; 'import': 0.24; 'header:User-Agent:1': 0.26; "doesn't": 0.26; 'example': 0.26; 'header:X-Complaints-To:1': 0.26; 'skip:( 20': 0.28; 'code': 0.30; 'probably': 0.31; 'included': 0.32; 'skip:_ 10': 0.32; 'class': 0.33; 'instances': 0.33; 'subject:use': 0.35; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'really': 0.37; 'received:org': 0.37; "won't": 0.38; 'copying': 0.38; 'skip:o 20': 0.38; 'to:addr:python.org': 0.40; 'received:de': 0.40; 'determine': 0.61 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd972e.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20+ Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:101396 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)]))