[Python-Dev] Add a frozendict builtin type (original) (raw)

Xavier Morel python-dev at masklinn.net
Mon Feb 27 22:13:37 CET 2012


On 2012-02-27, at 19:53 , Victor Stinner wrote:

Rationale =========

A frozendict type is a common request from users and there are various implementations. There are two main Python implementations: * "blacklist": frozendict inheriting from dict and overriding methods to raise an exception when trying to modify the frozendict * "whitelist": frozendict not inheriting from dict and only implement some dict methods, or implement all dict methods but raise exceptions when trying to modify the frozendict The blacklist implementation has a major issue: it is still possible to call write methods of the dict class (e.g. dict.set(myfrozendict, key, value)). The whitelist implementation has an issue: frozendict and dict are not "compatible", dict is not a subclass of frozendict (and frozendict is not a subclass of dict).

This may be an issue at the C level (I'm not sure), but since this would be a Python 3-only collection, "user" code (in Python) should/would generally be using abstract base classes, so type-checking would not be an issue (as in Python code performing isinstance(a, dict) checks naturally failing on frozendict)

Plus frozenset does not inherit from set, it's a whitelist reimplementation and I've never known anybody to care. So there's that precedent. And of course there's no inheritance relationship between lists and tuples.

* frozendict has not the following methods: clear, delitem, pop, popitem, setdefault, setitem and update. As tuple/frozenset has less methods than list/set.

It'd probably be simpler to define that frozendict is a Mapping (where dict is a MutableMapping). And that's clearer.

* Make dict inherits from frozendict

Isn't that the other way around from the statement above? Not that I'd have an issue with it, it's much cleaner, but there's little gained by doing so since isinstance(a, dict) will still fail if a is a frozendict.

* Add a frozendict abstract base class to collections?

Why? There's no dict ABC, and there are already a Mapping and a MutableMapping ABC which fit the bill no?



More information about the Python-Dev mailing list