immutables

Posted by Afsal on 24-Nov-2023

Hi Pythonistas!

Today we will learn a package called immutables. This is an immutable variation of the dictionary. The underlying data structure is a Hash Array Mapped Trie (HAMT) used in Clojure, Scala, Haskell, and other functional languages. Immutable mappings based on HAMT have O(log N) performance for both set() and get() operations, which is essentially O(1) for relatively small mappings. If try to modify the map an new map is created. Let us dive into the code

Installation

pip install immutables

Creating map

import immutables

map = immutables.Map(a=1, b=2)

print(map)

Output

immutables.Map({'a': 1, 'b': 2})

Accessing map

Accessing the immutable map is similar to the normal dictionary except the direct assignment

print(map['a'])

print(map.get('z', 100))

print('z' in map)

Output

1

100

False

Direction assignment

map["c"] = 2

Output

TypeError: 'immutables._map.Map' object does not support item assignment

Mutating maps

map2 = map.set("c", 3)
print("map2: ", map2)

map3 = map.set("a", 100)
print("map3: ", map3)

map4 = map.delete('b')
print("map4: ", map4)

print("map: ", map)

with map.mutate() as map5:
    map5["a"] = 100
    del map5["b"]
    map5.set('1', '2')
    map5.finish()

print("map5: ", map5)

print('map: ', map)

Output

map2:  immutables.Map({'c': 3, 'a': 1, 'b': 2})

map3:  immutables.Map({'a': 100, 'b': 2})

map4:  immutables.Map({'a': 1})

map:  immutables.Map({'a': 1, 'b': 2})

map5:  immutables.MapMutation({'1': '2', 'a': 100})

map:  immutables.Map({'a': 1, 'b': 2})

We can either mutate using the set method or first make the ready for mutation using mutate method and modify, If we use the mutate method we can use the direct assignments for the map

When it is useful

We can use this for configuration management, serialization, plugin development etc.

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in