Skip to main content

xmmutablemap

JAX-compatible Immutable Mapping

JAX prefers immutable objects, but before Python 3.15 there is no built-in immutable dictionary. 😢
This repository defines a light-weight immutable map (lower-level than a dict) that JAX understands as a PyTree. 🎉 🕶️ On Python 3.15+, prefer the built-in frozendict (see below).

Installation

PyPI platforms PyPI version

pip install xmmutablemap
using uv
uv add xmmutablemap
from source, using pip
pip install git+https://github.com/GalacticDynamics/xmmutablemap.git
building from source
cd /path/to/parent
git clone https://github.com/GalacticDynamics/xmmutablemap.git
cd xmmutablemap
pip install -e .  # editable mode

Documentation

xmutablemap provides the class ImmutableMap, which is a full implementation of Python's Mapping ABC. If you've used a dict then you already know how to use ImmutableMap! The things ImmutableMap adds is 1) immutability (and related benefits like hashability) and 2) compatibility with JAX.

from xmmutablemap import ImmutableMap

print(ImmutableMap(a=1, b=2, c=3))
# ImmutableMap({'a': 1, 'b': 2, 'c': 3})

print(ImmutableMap({"a": 1, "b": 2.0, "c": "3"}))
# ImmutableMap({'a': 1, 'b': 2.0, 'c': '3'})

Relationship to frozendict (PEP 814)

Python 3.15 adds a built-in frozendict (PEP 814), which covers most of what ImmutableMap was written for. ImmutableMap is now a subclass of it, so the two interoperate directly:

from xmmutablemap import ImmutableMap, frozendict

d = ImmutableMap(a=1, b=2)

print(isinstance(d, frozendict))
# True
print(d == frozendict(a=1, b=2) == {"a": 1, "b": 2})
# True

On Python 3.15+, xmmutablemap.frozendict is the built-in. On older Pythons it is a behaviour-matched stand-in, so this code works the same on every supported version and you can migrate ahead of your Python floor.

Prefer the built-in frozendict on Python 3.15+

Since JAX 0.11.2, JAX registers the built-in frozendict as a PyTree node. On Python 3.15+ with jax>=0.11.2, use the built-in frozendict directly; it does everything ImmutableMap does, with no extra dependency. ImmutableMap remains for Python < 3.15, where the built-in does not exist (and JAX treats xmmutablemap.frozendict, the stand-in, as an opaque leaf).

import jax

print(jax.tree.structure(ImmutableMap(a=1, b=2)))
# PyTreeDef(CustomNode(ImmutableMap[('a', 'b')], [*, *]))
print(jax.tree.structure(frozendict(a=1, b=2)))
# Python 3.15+, jax>=0.11.2: PyTreeDef(frozendict({'a': *, 'b': *}))
# older Pythons (the stand-in): PyTreeDef(*)

One deliberate difference: ImmutableMap | other merges any Mapping, while frozendict | other merges only a dict or frozendict (so, for example, a custom Mapping with no | of its own raises TypeError). Convert such mappings with dict(...) when switching to the built-in.

JAX Integration

One of the key benefits of ImmutableMap is its compatibility with JAX. Since it's immutable and hashable, it can be used in places where JAX would normally complain about mutable objects like regular dictionaries.

Using ImmutableMap as a Default in JAX Dataclasses

Here's an example showing how ImmutableMap can be used as a default value in a dataclass, which is particularly useful with JAX:

import functools
import jax
import jax.numpy as jnp
from dataclasses import dataclass
from xmmutablemap import ImmutableMap


@functools.partial(
    jax.tree_util.register_dataclass, data_fields=["params"], meta_fields=["batch_size"]
)
@dataclass(frozen=True)
class Config:
    """Configuration with immutable default parameters."""

    # This works! ImmutableMap is immutable and hashable
    params: ImmutableMap[str, float] = ImmutableMap(
        learning_rate=0.001, momentum=0.9, weight_decay=1e-4
    )
    batch_size: int = 32


# JAX can safely transform functions using this dataclass
@jax.jit
def train_step(config: Config, data: jnp.ndarray) -> jnp.ndarray:
    """Example training step that uses config parameters."""
    lr = config.params["learning_rate"]
    return data * lr


# This works perfectly
config = Config()
data = jnp.array([1.0, 2.0, 3.0])
result = train_step(config, data)
print(f"Result: {result}")
# Result: [0.001 0.002 0.003]

Key Benefits for JAX

  • Immutability: Once created, ImmutableMap cannot be modified, preventing accidental mutations that could break JAX's functional programming model
  • Hashability: JAX can safely cache and memoize functions that use ImmutableMap instances
  • PyTree Support: ImmutableMap is registered as a JAX PyTree, so it works seamlessly with JAX transformations like jit, grad, vmap, etc.
  • Safe Defaults: Can be used as default values in dataclasses without the typical pitfalls of mutable defaults

Development

Actions Status

We welcome contributions!

Metadata

Release files for xmmutablemap 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xmmutablemap 0.3.0
File Size Uploaded
xmmutablemap-0.3.0.tar.gz 175.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for xmmutablemap 0.3.0
File Interpreter ABI Platform
xmmutablemap-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 188.5 kB

Release files / xmmutablemap-0.3.0.tar.gz

Download URL xmmutablemap-0.3.0.tar.gz
Size 175.4 kB
Tags Source
SHA-256 checksum
How to use checksums
b7ef5fe4d2b9384caed8960caafe6ac1533796e63cc365530c3ab373deb93bcb
BLAKE2b-256 checksum
How to use checksums
879a911df791a061581d7f489e47014b58fe4481fb18bc42fd766878c5e8b6b9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.

Transparency log

Release files / xmmutablemap-0.3.0-py3-none-any.whl

Download URL xmmutablemap-0.3.0-py3-none-any.whl
Size 13.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3d3d488c9cac3928750c49305fc84f61c22f3281bd30718654734312ab1b3b1f
BLAKE2b-256 checksum
How to use checksums
f7fd83a629140db9a35e4bdb54f85dee79ea800d425c86a99cb533dcf02adfdf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.

Transparency log

Release history Release notifications | RSS feed

0.3.1

2 release files

This release

0.3.0 This release

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page