Hashable Dict

from dgisim import HashableDict
class HashableDict(*args, frozen=True, **kwargs)

Bases: dict, Mapping[_T, _U]

Inheritates dict but implements __hash__().

In order to safely use __hash__(), there’s a boolean property _frozen, determining whether the HashableDict is safe to hash and accept further modifications. The default value of _frozen is True.

If you want to create the HashableDict, make some modifications and then freeze it, add a keyword argument frozen=False when initializing, and call .freeze() later.

You cannot call any setter, deleter or hash method of a frozen HashableDict. If you do so, Exception will be raised.

Note that though __add__ and __sub__ are overriden, but they are designed for int values only!

freeze() None

Freeze this HashableDict to prevent further changes and enable hash.

classmethod from_dict(d: dict[_T, _U]) HashableDict[_T, _U]

This method is preferred when trying to copy a HashableDict than __init__()

to_dict() dict[_T, _U]
Returns:

a dictionary of the same content.

Examples of some operations

from dgisim import HashableDict

dict1 = HashableDict((('a', 0), ('b', 1)))
dict2 = HashableDict({'c': 0, 'b': 1})

assert dict1 == dict2
assert hash(dict1) == hash(dict2)
assert dict1 + dict2 == HashableDict({'b': 2})
assert dict1 - dict2 == HashableDict(())