python - What would a "frozen dict" be? -


  • a frozen set frozenset.
  • a frozen list tuple.
  • what frozen dict be? immutable, hashable dict.

i guess collections.namedtuple, more frozen-keys dict (a half-frozen dict). isn't it?

a "frozendict" should frozen dictionary, should have keys, values, get, etc., , support in, for, etc.

python doesn't have builtin frozendict type. turns out wouldn't useful (though still useful more frozenset is).

the common reason want such type when memoizing function calls functions unknown arguments. common solution store hashable equivalent of dict (where values hashable) tuple(sorted(kwargs.iteritems())).

this depends on sorting not being bit insane. python cannot positively promise sorting result in reasonable here. (but can't promise else, don't sweat much.)


you enough make sort of wrapper works dict. might like

import collections  class frozendict(collections.mapping):     """don't forget docstrings!!"""      def __init__(self, *args, **kwargs):         self._d = dict(*args, **kwargs)         self._hash = none      def __iter__(self):         return iter(self._d)      def __len__(self):         return len(self._d)      def __getitem__(self, key):         return self._d[key]      def __hash__(self):         # have been simpler , maybe more obvious          # use hash(tuple(sorted(self._d.iteritems()))) discussion         # far, solution o(n). don't know kind of          # n going run into, it's hard resist          # urge optimize when gain improved algorithmic performance.         if self._hash none:             self._hash = 0             pair in self.iteritems():                 self._hash ^= hash(pair)         return self._hash 

it should work great:

>>> x = frozendict(a=1, b=2) >>> y = frozendict(a=1, b=2) >>> x y false >>> x == y true >>> x == {'a': 1, 'b': 2} true >>> d = {x: 'foo'} >>> d[y] 'foo' 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -