__new__ and __init__ - why does this work?

Ian Pilcher arequipeno at gmail.com
Tue Aug 8 20:08:16 EDT 2017


I have created a class to provide a "hash consing"[1] set.

   class UniqueSet(frozenset):

       _registry = dict()

       def __new__(cls, *args, **kwargs):
           set = frozenset(*args, **kwargs)
           try:
               return UniqueSet._registry[set]
           except KeyError:
               self = super(UniqueSet, cls).__new__(cls, *args, **kwargs)
               UniqueSet._registry[set] = self
               return self

       def __init__(self, *args, **kwargs):
           pass

I can't figure out how it works, though.  In particular, I can't figure
out how the call to __new__ actually initializes the set (since my
__init__ never calls the superclass __init__).

Is this a particular behavior of frozenset, or am I missing something
about the way that __new__ and __init__ interact?

-- 
========================================================================
Ian Pilcher                                         arequipeno at gmail.com
-------- "I grew up before Mark Zuckerberg invented friendship" --------
========================================================================




More information about the Python-list mailing list