Skip to content

Python 3.15 frozendict Tutorial: Create Immutable Dictionaries

Learn how to use Python 3.15's built-in frozendict to create immutable mappings, build hashable configuration keys, cache function results and update type checks safely.

Python 3.15 frozendict Tutorial: Create Immutable Dictionaries

On this page

A Python dictionary can hold configuration settings, request options or application defaults, but any part of your program can change its contents after creation. That is useful when data needs updating, but risky when a function expects its input to remain stable. Python 3.15 adds a built-in answer: frozendict, an immutable mapping that can also be used as a dictionary key when its contents are hashable. This tutorial shows how to create one, combine it with ordinary dictionaries, and use it with cached functions.

What Python 3.15 changes with frozendict

Before Python 3.15, developers who needed a read-only mapping generally used a third-party package or types.MappingProxyType. Python now includes frozendict directly in the built-in namespace, so there is no package to install or import. It behaves like a dictionary for common reading operations, but it does not provide methods that change its contents. The feature was introduced through Python Enhancement Proposal 814, which describes the type and its intended uses.

There is an important distinction from an ordinary dictionary: frozendict is not a subclass of dict. It implements the mapping interface, which means it supports familiar operations such as reading values, iterating over keys and checking membership. Code that explicitly tests whether an object is a dict may therefore need updating. The broader mapping interface is usually a better choice when a function should accept different dictionary-like objects.

Check that your Python version supports frozendict

The built-in type was added in Python 3.15, so a Python 3.14 installation will not recognize its constructor. Check the interpreter used by your project rather than relying on the version installed elsewhere on your computer. Run this command in the same terminal or virtual environment that runs your application:

python --version

The result should identify Python 3.15 or a later compatible release. You can also check the feature directly inside the interpreter:

print(frozendict({"mode": "production"}))

If the command raises a NameError, the interpreter probably predates Python 3.15 or the application is running under a different Python installation. Confirm the active interpreter before changing your project dependencies.

Create an immutable dictionary from existing data

The simplest constructor accepts keyword arguments, just like a regular dictionary. Use it when the keys and values are already known and you want a compact declaration:

settings = frozendict(
 theme="dark",
 language="en",
 notifications=True
)

print(settings["theme"])
print("language" in settings)
print(list(settings.keys()))

The result can be read and iterated over, but assignments are rejected. This is useful for settings that should remain fixed while several parts of an application read them. The constructor also accepts an existing mapping or an iterable of key-value pairs, so you do not have to rewrite data that already exists.

defaults = {
 "timeout": 30,
 "retries": 3
}

config = frozendict(defaults)

print(config["timeout"])
print(config.get("retries"))

Creating a frozendict from an ordinary dictionary copies its entries into a new mapping. It is a shallow copy, however: if a value is itself a mutable object, that nested object is not automatically frozen. The outer mapping cannot be reassigned, but a mutable object stored inside it may still be changed.

See what happens when you try to modify it

The most obvious difference appears when code attempts to assign a new value. A normal dictionary accepts the operation, while a frozendict raises a TypeError. It also does not provide dictionary methods such as update(), pop() or clear(), because those operations would change the mapping.

profile = frozendict(
 username="sam",
 role="editor"
)

# This raises TypeError:
profile["role"] = "admin"

# These mutation methods are not available:
# profile.update({"role": "admin"})
# profile.pop("username")

When an application needs a changed configuration, create a new mapping instead of trying to edit the existing one. The union operator provides a concise way to combine mappings while preserving the immutable result:

base = frozendict(
 host="localhost",
 port=8000
)

updated = base | {"port": 9000}

print(base["port"])
print(updated["port"])

The original mapping remains unchanged, while updated contains the replacement value. This makes the change explicit and helps prevent one part of a program from silently altering configuration another part still relies on.

Use frozendict as a dictionary key or set element

Ordinary dictionaries cannot be used as keys in another dictionary because they are mutable and therefore unhashable. A frozendict can be hashed when all its keys and values are hashable. Hashable objects have a stable value that Python can use in dictionaries and sets, which makes immutable mappings useful for representing combinations of options.

request_a = frozendict(
 method="GET",
 region="eu"
)

request_b = frozendict(
 method="POST",
 region="eu"
)

request_cache = {
 request_a: "cached response A",
 request_b: "cached response B"
}

print(request_cache[request_a])

This approach can be useful when a program stores results for different combinations of settings. For example, a data-processing application might distinguish results by output format and region. Instead of converting each configuration into a custom string, it can use a frozen mapping as the key.

There is a restriction: every value must be hashable before the entire mapping can be hashed. Strings, integers and tuples containing hashable items are suitable, but lists and ordinary dictionaries are not. A frozendict containing a list can still be created and read; calling hash() on it will fail.

Cache function results with immutable arguments

Python's functools.lru_cache stores previous function results so repeated calls with the same arguments can reuse earlier work. Its arguments must be hashable, which is why passing an ordinary dictionary to a cached function causes a problem. A frozendict with hashable contents can solve that specific limitation.

from functools import lru_cache

@lru_cache(maxsize=128)
def get_endpoint(options):
 region = options["region"]
 version = options["version"]
 return f"/{region}/api/{version}"

options = frozendict(
 region="eu",
 version="v2"
)

print(get_endpoint(options))
print(get_endpoint(options))

The second call can reuse the cached result because it receives an equivalent hashable argument. The cache limit of 128 means the decorator retains up to 128 recent argument-and-result combinations, rather than allowing this particular cache to grow without a bound. This pattern is useful when configuration objects are repeatedly passed into expensive functions.

Do not use a frozen mapping as a cache key if its values contain mutable or otherwise unhashable objects. Also remember that a cache is only correct when the function's result depends on the arguments represented by its cache key. If the function also relies on changing external state, caching may return an outdated result even though the mapping itself is immutable.

Choose between frozendict and MappingProxyType

Python already had a read-only mapping tool called MappingProxyType. It is not interchangeable with frozendict. A mapping proxy is a read-only view of another mapping, so changes made to the original dictionary remain visible through the proxy. A frozendict, by contrast, stores its own shallow copy of the supplied entries and does not reflect later changes to the source dictionary.

from types import MappingProxyType

source = {"mode": "development"}

proxy = MappingProxyType(source)
frozen = frozendict(source)

source["mode"] = "production"

print(proxy["mode"])
print(frozen["mode"])

The proxy displays the updated value because it follows the original dictionary. The frozen mapping retains the value it received when it was created. Choose MappingProxyType when you want callers to read a live mapping without changing it through that view. Choose frozendict when you want an independent, immutable mapping that may also be hashable.

Update type checks when accepting frozen mappings

Because frozendict is not a subclass of dict, older functions that use isinstance(value, dict) will reject it. That check is narrower than many programs actually need. If a function only reads keys and values, checking against the standard mapping interface makes it compatible with ordinary dictionaries, frozen dictionaries and other mapping implementations.

from collections.abc import Mapping

def describe_config(config):
 if not isinstance(config, Mapping):
 raise TypeError("Expected a mapping")

 for key, value in config.items():
 print(key, value)

describe_config({"debug": True})
describe_config(frozendict(debug=False))

If your function genuinely requires a mutable dictionary, keep the stricter check and make that requirement clear. If it only reads data, the mapping interface communicates the actual contract more accurately. This small change can make a library easier to extend without forcing callers to convert every mapping into a regular dictionary.

Know the limits before replacing every dictionary

frozendict is most useful for fixed configuration, cache keys and values that should not be reassigned after construction. It is not a universal replacement for dict. Code that needs to add entries, remove keys or update values should continue using a normal dictionary, and code that expects a live read-only view may be better served by MappingProxyType.

Immutability is also shallow rather than recursive. If a frozen mapping contains a list, the list can still change; if it contains another ordinary dictionary, that nested dictionary can still be edited. For deeply immutable data, the nested values must also be converted into immutable types, such as tuples or other frozen mappings. That distinction matters when using these objects as cache keys or sharing them across components.

Start by converting one configuration object that should never change after setup. Test its equality, hashing and compatibility with the functions that consume it before extending the pattern across a codebase. Python 3.15 gives developers a standard immutable mapping, but the best result comes from choosing it only where the program benefits from data that stays fixed.

Muhammad Saleem profile photo

Written by

Muhammad Saleem

I’m Muhammad Saleem, a web developer and the owner of TechWare House, a software house focused on practical web and software solutions. With over 14 years of experience, I’ve built and managed hundreds of websites and custom , PHP/MySQL, Python, Django applications. I share hands-on insights about web development, software, technology, and digital solutions on WizTechnoz.com

148 posts published

All posts by this author

Copy this post

0 Comments

No comments yet. Be the first to share your thoughts.

Join the conversation

Log in or create a free account to leave a comment. You can edit or delete your own comments any time.