[Python-ideas] Revisiting Immutable Mappings

Jonathan Fine jfine2358 at gmail.com
Thu Oct 11 08:51:46 EDT 2018

Steve D'Aprano wrote

> Zaur Shibzukhov wrote
> > class frozendict(dict):
> This violates the Liskov Substitution Principle.
> https://en.wikipedia.org/wiki/Liskov_substitution_principle

and so, Steve said, we should not make frozendict a subclass of dict.

Perhaps Zaur was thinking of Don't Repeat Yourself (DRY)

Certainly, by writing

   class frozendict(dict):
       # methods

Zaur was able to use unchanged superclass methods such as __init__ and
__getitem__, and also to delegate most of __str__ to the superclass.

I see much merit in both


I wonder whether, in pure Python, we can nicely have them both, when
we implement frozenset. The best I can come up with is (not tested) is

class frozendict:
    __slots__ = ('_self',)

    def __init__(self, *argv, **kwargs):
        self._self = dict(*argv, **kwargs)

    def __getitem__(self, key):
        return self._self.__getitem__(key)

    # And so on.


More information about the Python-ideas mailing list