[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)
https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

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

https://en.wikipedia.org/wiki/Liskov_substitution_principle
https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

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.

-- 
Jonathan


More information about the Python-ideas mailing list