A freezable dictionary for python.

March 12 2019
Keywords: python,dictionary

A freezable dictionary for python.

Check it out!

This repo provides a single class, a freezable dict, FreezableDict.

A FreezableDict is basically identical to a regular dict, but it offers the additional possibility of freezing for use as a dictionary key, set item, etc.

I stole most of the idea from this stack answer so props to Mike.

Install

Pypi:

1
pip install freezable_dict

For the bleeding edge:

1
pip install git+https://github.com/nolanbconaway/freezable_dict.git

Usage

Import.

1
>>> from freezable_dict import FreezableDict

Regular dict stuff works as usual.

1
2
3
4
5
6
>>> d = FreezableDict(a=1, b=2)
>>> for k, v in d.items():
...     print(k, v)
...
a 1
b 2

Freeze your dict and you can use it as a set item, dictionary key, etc. But you can’t mutate it.

1
2
3
4
5
6
7
8
9
>>> d = FreezableDict(a=1, b=2).freeze()
>>> set([d])
{{'a': 1, 'b': 2}}
>>> try:
...     d['c'] = 3
... except TypeError as e:
...     print(e)
...
Frozen dicts cannot be changed. thaw to proceed.

Thaw out a frozen dict and you can mutate it as usual, but TypeError is thrown when you try to use the frozen stuff.

1
2
3
4
5
6
7
8
9
10
>>> d = FreezableDict(a=1, b=2).freeze()
>>> d.thaw()
{'a': 1, 'b': 2}
>>> d['c'] = 3
>>> try:
...     set([d])
... except TypeError as e:
...     print(e)
...
Thawed dicts do not hash. freeze me to proceed.