Immutable Collections

0.21 · active · verified Thu Apr 09

The `immutables` library for Python provides a high-performance immutable mapping type, `immutables.Map`, built on a Hash Array Mapped Trie (HAMT) data structure. It offers efficient (O(log N)) operations for setting and getting values, making it suitable for functional programming paradigms and scenarios where data integrity and thread safety are paramount. The current version is 0.21. It follows a release cadence driven by bug fixes and performance improvements.

Warnings

Install

Imports

Quickstart

Demonstrates creating an `immutables.Map`, performing individual `set` and `delete` operations which return new map instances, and using the `mutate()` context manager for efficient batch updates.

import immutables

# Create an immutable map
my_map = immutables.Map({"a": 1, "b": 2})
print(f"Original Map: {my_map}")

# Set a value (returns a *new* map)
new_map = my_map.set("c", 3)
print(f"Map after setting 'c': {new_map}")
print(f"Original map is unchanged: {my_map}")

# Delete a value (returns a *new* map)
map_after_delete = new_map.delete("b")
print(f"Map after deleting 'b': {map_after_delete}")

# Batch mutations using a context manager for efficiency
with my_map.mutate() as mutable_map:
    mutable_map["d"] = 4
    del mutable_map["a"]
    mutable_map["e"] = 5
batch_mutated_map = mutable_map.finish()
print(f"Map after batch mutations: {batch_mutated_map}")

view raw JSON →