[Python-Dev] Another case for frozendict (original) (raw)
Eric Snow ericsnowcurrently at gmail.com
Wed Jul 16 16:27:51 CEST 2014
- Previous message: [Python-Dev] Another case for frozendict
- Next message: [Python-Dev] Another case for frozendict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Wed, Jul 16, 2014 at 7:47 AM, R. David Murray <rdmurray at bitdance.com> wrote:
After I hit send on my previous message, I thought more about your example. One of the issues here is that modifying the dict breaks an invariant of the API. I have a similar situation in the email module, and I used the same solution you did in regex: always return a new dict. It would be nice to be able to return a frozendict instead of having the overhead of building a new dict on each call. That by itself might not be enough reason. But, if the user wants to use the data in modified form elsewhere, they would then have to construct a new regular dict out of it, making the decision to vary the data from what matches the state of the object it came from an explicit one. That seems to fit the Python zen ("explicit is better than implicit").
So I'm changing my mind, and do consider this a valid use case, even absent the crash.
+1
A simple implementation is pretty straight-forward:
class FrozenDict(Mapping): def init(self, *args, **kwargs): self._map = dict(*args, **kwargs) self._hash = ... def hash(self): return self._hash def len(self): return len(self._map) def iter(self): yield from self._map def getitem(self, key): return self._map[key]
This is actually something I've used before on a number of occasions. Having it in the stdlib would be nice (though that alone is not sufficient for inclusion :)). If there is a valid use case for a frozen dict type in other stdlib modules, I'd consider that a pretty good justification for adding it.
Incidentally, collections.abc.Mapping is the only one of the 6 container ABCs that does not have a concrete implementation (not counting types.MappingProxyType which is only a proxy).
-eric
- Previous message: [Python-Dev] Another case for frozendict
- Next message: [Python-Dev] Another case for frozendict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]