Managing data safely is an important part of building reliable Python applications. Dictionaries are among the most commonly used data structures in Python because they allow developers to store and access information using key-value pairs. However, dictionaries are mutable, which means their contents can be changed after creation.
This flexibility is useful in many situations, but it can also introduce problems when data should remain unchanged. For example, application configuration, shared settings, cached values, and predefined business rules should not always be modified accidentally by different parts of an application.
Before Python 3.15, developers commonly used techniques such as MappingProxyType, tuples, or third-party libraries to create read-only mappings. These approaches worked, but they had different limitations, particularly when hashability and reusable immutable data were required.
Python 3.15 introduces a built-in frozendict type through PEP 814. It provides an immutable dictionary-like mapping that prevents changes to its contents after creation. It also supports hashing when all its keys and values are hashable, making it useful in situations where ordinary dictionaries cannot be used.
In this article, we will explore frozendict in Python 3.15, understand how it works, and see how to use it in practical application scenarios.
What Is frozendict in Python 3.15?
The frozendict type is a built-in immutable mapping introduced in Python 3.15.
It provides functionality similar to a regular dictionary but does not allow developers to add, remove, or replace entries after creation.
Consider a normal dictionary:
user = {
"name": "John",
"role": "Developer"
}
user["role"] = "Administrator"
print(user)
Output:
{'name': 'John', 'role': 'Administrator'}
A regular dictionary allows modifications.
Now consider the same data using frozendict:
user = frozendict({
"name": "John",
"role": "Developer"
})
print(user)
Output:
frozendict({'name': 'John', 'role': 'Developer'})
If developers attempt to modify it, Python raises a TypeError.
user = frozendict({
"name": "John",
"role": "Developer"
})
user["role"] = "Administrator"
The operation fails because frozendict does not support item assignment.
This makes it useful when application data should remain unchanged after initialization.
Why Python Introduced frozendict
Python dictionaries are designed for mutable data.
Developers can add new entries, remove existing entries, and update values whenever required.
However, not every application object should be mutable.
Consider a configuration dictionary:
APP_CONFIG = {
"environment": "production",
"debug": False,
"max_connections": 100
}
If this dictionary is shared across multiple modules, any module can modify its values.
For example:
APP_CONFIG["debug"] = True
An accidental modification could change application behavior.
Before Python 3.15, developers had several alternatives.
One option was MappingProxyType:
from types import MappingProxyType
config = {
"environment": "production",
"debug": False
}
readonly_config = MappingProxyType(config)
Another option was to use a third-party immutable mapping library.
Python 3.15 introduces frozendict as a built-in solution.
config = frozendict({
"environment": "production",
"debug": False,
"max_connections": 100
})
This provides a dedicated immutable mapping without requiring an external dependency.
The addition is defined by PEP 814, which introduces frozendict as a standard built-in type.
Creating a frozendict Object
Python 3.15 supports multiple ways to create a frozendict.
Creating an Empty frozendict
Developers can create an empty immutable mapping using the constructor.
settings = frozendict()
print(settings)
Output:
frozendict({})
The resulting object contains no entries.
Creating a frozendict From a Dictionary
An existing dictionary can be passed to the constructor.
user = {
"id": 101,
"name": "Sarah",
"role": "Editor"
}
readonly_user = frozendict(user)
print(readonly_user)
Output:
frozendict({'id': 101, 'name': 'Sarah', 'role': 'Editor'})
The constructor creates a new mapping containing the entries from the original dictionary.
Changing the original dictionary later does not add or remove entries from the frozendict.
Creating a frozendict Using Keyword Arguments
Developers can also initialize the mapping using keyword arguments.
database_config = frozendict(
host="localhost",
port=5432,
database="application"
)
print(database_config)
This is a convenient approach when creating small configuration objects.
Creating a frozendict From Key-Value Pairs
The constructor also accepts an iterable containing key-value pairs.
product = frozendict([
("id", 101),
("name", "Laptop"),
("price", 75000)
])
print(product)
This approach is useful when data is generated dynamically from another iterable.
Understanding the Immutability of frozendict
The main purpose of frozendict is to prevent changes to its mapping entries after creation.
It does not support the mutation methods available on ordinary dictionaries.
Consider the following example:
settings = frozendict({
"debug": False,
"timeout": 30
})
settings["debug"] = True
Python raises a TypeError because item assignment is not supported.
The same applies to deletion:
del settings["timeout"]
Other dictionary mutation methods, such as clear(), pop(), popitem(), setdefault(), and update(), are also unavailable.
The following table summarizes the difference.
Operation | dict | frozendict |
|---|
Read values | Supported | Supported |
Add entries | Supported | Not supported |
Update entries | Supported | Not supported |
Delete entries | Supported | Not supported |
Iterate over keys | Supported | Supported |
Iterate over values | Supported | Supported |
Iterate over items | Supported | Supported |
Hashable | No | When all keys and values are hashable |
Preserves insertion order | Yes | Yes |
One important distinction is that frozendict is not a subclass of dict. It implements the collections.abc.Mapping protocol and inherits directly from object.
This means code that specifically checks isinstance(value, dict) will not automatically recognize a frozendict instance.
For reusable application code, checking against collections.abc.Mapping is often a better approach when both mutable and immutable mappings are acceptable.
Accessing Values From frozendict
Although frozendict does not allow modifications, developers can read its contents in much the same way as a regular dictionary.
Accessing Values Using Keys
user = frozendict({
"name": "John",
"role": "Developer"
})
print(user["name"])
print(user["role"])
Output:
John
Developer
Using the get() Method
The get() method works similarly to the dictionary implementation.
user = frozendict({
"name": "John",
"role": "Developer"
})
print(user.get("name"))
print(user.get("department", "Not Assigned"))
Output:
John
Not Assigned
Iterating Over Entries
Developers can use keys(), values(), and items() to access mapping contents.
user = frozendict({
"name": "Sarah",
"role": "Editor",
"active": True
})
for key, value in user.items():
print(f"{key}: {value}")
Output:
name: Sarah
role: Editor
active: True
These operations make frozendict convenient for read-only application data.
Understanding Hashability in frozendict
One of the most useful features of frozendict is its support for hashing.
Normal dictionaries cannot be used as dictionary keys or stored in sets because they are mutable and unhashable.
For example:
config = {
"environment": "production",
"debug": False
}
print(hash(config))
This raises a TypeError because dictionaries are unhashable.
Python 3.15 allows frozendict objects to be hashed when all their keys and values are hashable.
Consider the following example:
config = frozendict({
"environment": "production",
"debug": False
})
print(hash(config))
The operation succeeds because the keys and values in this mapping are hashable.
The resulting hash can be used in a set or as a dictionary key.
config1 = frozendict(
environment="production",
debug=False
)
config2 = frozendict(
environment="development",
debug=True
)
configurations = {
config1,
config2
}
print(len(configurations))
Output:
2
This is useful when an application needs to represent immutable configuration combinations or use immutable mappings as cache keys.
However, developers should remember that hashability depends on the contents.
A frozendict containing a list or another unhashable value cannot be hashed.
For example:
data = frozendict({
"name": "John",
"skills": ["Python", "SQL"]
})
print(hash(data))
This raises a TypeError because the list stored under skills is unhashable.
Shallow Immutability: An Important Concept
One of the most important things to understand about frozendict is that its immutability is shallow.
This means that the mapping itself cannot be modified, but mutable objects stored inside it can still change.
Consider the following example:
user = frozendict({
"name": "John",
"skills": ["Python", "Java"]
})
user["skills"].append("C#")
print(user)
Output:
frozendict({
'name': 'John',
'skills': ['Python', 'Java', 'C#']
})
The mapping structure remains unchanged, but the list stored as a value is mutable.
This behavior is important when designing applications that share data between multiple components.
If nested data must also remain immutable, developers should use immutable values or recursively convert nested structures.
For example:
def freeze(value):
if isinstance(value, dict):
return frozendict({
key: freeze(item)
for key, item in value.items()
})
if isinstance(value, list):
return tuple(
freeze(item)
for item in value
)
if isinstance(value, set):
return frozenset(
freeze(item)
for item in value
)
return value
user = freeze({
"name": "John",
"skills": ["Python", "Java"],
"settings": {
"active": True
}
})
print(user)
This example recursively converts dictionaries, lists, and sets into immutable equivalents.
For production use, the function should also define how it handles custom objects, circular references, and other collection types.
Practical Example: Managing Application Configuration
Application configuration is one of the most common use cases for immutable mappings.
Consider a backend application that stores environment settings.
APP_CONFIG = frozendict({
"environment": "production",
"debug": False,
"database_host": "localhost",
"database_port": 5432,
"max_connections": 100
})
def get_database_settings():
return frozendict({
"host": APP_CONFIG["database_host"],
"port": APP_CONFIG["database_port"],
"max_connections": APP_CONFIG["max_connections"]
})
database_settings = get_database_settings()
print(database_settings)
The application can safely expose these configuration mappings to different modules without allowing accidental changes to their entries.
This is useful for:
Application configuration.
Database connection settings.
Feature flag definitions.
Default application preferences.
Read-only service metadata.
However, frozendict should not be treated as a security boundary. It prevents ordinary mapping mutations, but it does not protect secrets from being read or prevent mutable nested values from changing.
Using frozendict With Dictionary Operations
Although frozendict does not support modifications, it provides several operations that make it convenient to work with mapping data.
Using the keys(), values(), and items() Methods
These methods provide access to the mapping contents.
settings = frozendict({
"theme": "dark",
"language": "en",
"notifications": True
})
print(list(settings.keys()))
print(list(settings.values()))
print(list(settings.items()))
These methods behave similarly to their dictionary counterparts.
Using the fromkeys() Method
Python 3.15 also provides fromkeys() for creating a frozendict from a collection of keys.
permissions = frozendict.fromkeys(
["read", "write", "delete"],
False
)
print(permissions)
Output:
frozendict({
'read': False,
'write': False,
'delete': False
})
This is useful when initializing a collection of permissions or feature flags with a common default value.
Combining Two frozendict Objects
Python 3.15 supports the union operator for combining mappings.
default_config = frozendict({
"debug": False,
"timeout": 30
})
custom_config = frozendict({
"timeout": 60,
"environment": "production"
})
final_config = default_config | custom_config
print(final_config)
Output:
frozendict({
'debug': False,
'timeout': 60,
'environment': 'production'
})
When both mappings contain the same key, the value from the right-hand mapping takes precedence.
The original objects remain unchanged.
The |= operator also produces a new frozendict rather than modifying the existing mapping in place.
This behavior is important when sharing immutable configuration between different application components.
Using frozendict With functools.lru_cache()
Caching is another useful application of immutable mappings.
Python's functools.lru_cache() requires function arguments to be hashable because it uses them as cache keys.
A regular dictionary cannot be passed directly as an argument to a cached function.
Consider the following example:
from functools import lru_cache
@lru_cache()
def calculate_total(config):
return config["price"] * config["quantity"]
config = {
"price": 100,
"quantity": 5
}
print(calculate_total(config))
This raises a TypeError because a dictionary is unhashable.
With frozendict, the same approach works when all keys and values are hashable.
from functools import lru_cache
@lru_cache()
def calculate_total(config):
return config["price"] * config["quantity"]
config = frozendict({
"price": 100,
"quantity": 5
})
print(calculate_total(config))
Output:
500
If the same configuration is passed again, the cached result can be reused.
This is useful for applications that repeatedly calculate results using the same immutable configuration.
However, developers should remember that frozendict uses value-based hashing and equality. Two mappings with equal contents can share the same cache entry, regardless of their insertion order.
Also, only hashable keys and values are supported for hashing. A frozendict containing a list cannot be used as an lru_cache argument.
Using frozendict as a Function Default Argument
Mutable default arguments are a common source of unexpected behavior in Python.
Consider this example:
def create_user(name, settings={}):
settings["name"] = name
return settings
The same dictionary is reused across function calls because default arguments are evaluated once when the function is defined.
This can lead to unexpected shared state.
Developers commonly solve this problem by using None as the default value.
Python 3.15 also makes it possible to use frozendict when a function needs a shared immutable default configuration.
DEFAULT_SETTINGS = frozendict({
"theme": "light",
"notifications": True,
"language": "en"
})
def get_user_settings(settings=DEFAULT_SETTINGS):
return settings
user_settings = get_user_settings()
print(user_settings)
Because the default mapping cannot be modified, accidental changes to its entries are prevented.
If an operation requires modifying settings, create a separate dictionary:
def update_user_settings(settings, changes):
updated = dict(settings)
updated.update(changes)
return frozendict(updated)
new_settings = update_user_settings(
DEFAULT_SETTINGS,
{"theme": "dark"}
)
print(new_settings)
The original default configuration remains unchanged.
Using frozendict With JSON Serialization
Python 3.15 also updates several standard library modules to support frozendict.
One useful example is the json module.
Consider the following code:
import json
user = frozendict({
"id": 101,
"name": "John",
"role": "Developer"
})
json_data = json.dumps(user)
print(json_data)
Output:
{"id": 101, "name": "John", "role": "Developer"}
This makes frozendict convenient when working with read-only application data that needs to be converted into JSON.
The standard library also includes support for frozendict in modules such as copy, decimal, marshal, pickle, pprint, and xml.etree.ElementTree, with module-specific support for their respective operations.
For plistlib, the documented support applies to serialization.
This broader compatibility makes frozendict more practical than a custom immutable mapping implementation.
frozendict vs. MappingProxyType vs. Regular Dictionary
Python developers already have different options for working with dictionary-like data.
Understanding their differences helps when choosing the appropriate structure.
Feature | dict | frozendict | MappingProxyType |
|---|
Mutable entries | Yes | No | No |
Built into Python | Yes | Python 3.15 | Yes |
Hashable | No | When keys and values are hashable | No |
Implements Mapping | Yes | Yes | Yes |
Is a dict subclass | Yes | No | No |
Reflects changes to original dictionary | Not applicable | No | Yes |
Suitable for cache keys | No | Yes, when hashable | No |
Supports item assignment | Yes | No | No |
When Should You Use dict?
Use a regular dictionary when application data needs to change.
Examples include:
When Should You Use frozendict?
Use frozendict when mapping entries should remain unchanged after creation.
Examples include:
Application configuration.
Immutable cache keys.
Shared default settings.
Read-only application metadata.
Predefined business rules.
When Should You Use MappingProxyType?
MappingProxyType is useful when you need a read-only view of an existing dictionary.
For example:
from types import MappingProxyType
original = {
"debug": False
}
readonly = MappingProxyType(original)
original["debug"] = True
print(readonly["debug"])
Output:
True
The proxy prevents modifications through the proxy itself, but changes to the original dictionary remain visible.
frozendict behaves differently because it creates its own mapping from the supplied data rather than exposing a live view of the original dictionary.
Advantages of frozendict
The new built-in type provides several practical benefits for Python applications.
Prevents Accidental Mapping Changes
Once created, the mapping entries cannot be added, replaced, or deleted.
This is useful when multiple components need access to the same configuration.
Supports Hashing
When all keys and values are hashable, frozendict can be used as a dictionary key or set element.
This makes it useful for caching and memoization.
Built Into Python
Developers do not need to install a separate package to create immutable mappings.
Supports Standard Mapping Operations
It supports common read operations such as keys(), values(), items(), get(), and iteration.
This makes it relatively straightforward to adopt in existing Python applications.
Preserves Insertion Order
Like regular dictionaries, frozendict preserves the insertion order of its entries.
This is useful when predictable iteration order is required.
Supports Serialization
Python 3.15 updates several standard library modules to work with frozendict.
This makes it easier to use immutable mappings in data processing and serialization workflows.
Disadvantages and Limitations of frozendict
Although frozendict is useful, developers should understand its limitations.
Requires Python 3.15
The built-in type is not available in earlier Python versions.
Applications supporting Python 3.14 or older need an alternative.
Shallow Immutability
The mapping cannot be changed, but mutable objects stored inside it can still be modified.
Developers must use immutable nested values when complete immutability is required.
Hashing Requires Hashable Values
A frozendict containing lists, dictionaries, or other unhashable values cannot be hashed.
It can still be used as an immutable mapping, but not as a hash-based collection key.
Not a dict Subclass
Code that checks isinstance(value, dict) will not recognize frozendict.
Developers should use collections.abc.Mapping when they want to support different mapping implementations.
Creating Updated Data Requires a New Object
Since existing entries cannot be modified, updating data requires creating another mapping.
This is appropriate for immutable data but may be less convenient when frequent modifications are required.
Best Practices for Using frozendict in Production
The following practices can help developers use frozendict effectively.
Use frozendict for data that should not change. Avoid replacing every dictionary in an application with an immutable mapping.
Understand shallow immutability. Convert nested dictionaries, lists, and sets into immutable equivalents when nested data must also remain unchanged.
Check hashability before using frozendict as a cache key. Every key and value must be hashable for the mapping itself to be hashable.
Use collections.abc.Mapping for reusable function parameters. This allows functions to accept dict, frozendict, and other mapping implementations.
Avoid unnecessary object recreation. Create a new frozendict only when application data actually needs to change.
Use immutable defaults for shared configuration. This helps prevent accidental modifications to default application settings.
Validate data before freezing it. Immutability does not guarantee that the original values are correct or safe.
Use MappingProxyType for live read-only views. If changes to an underlying dictionary should remain visible, a mapping proxy is more appropriate.
Test nested objects separately. Verify that mutable values inside a frozendict cannot introduce unexpected shared-state changes.
Check Python compatibility. Make sure the application runtime and deployment environment support Python 3.15.
Use frozendict for hash-based caching only when appropriate. Consider the memory and hashing costs of large mappings.
Keep mutable and immutable responsibilities separate. Use regular dictionaries for changing application state and frozendict for stable mapping data.
Common Mistakes Developers Should Avoid
Assuming frozendict Is a dict
The following check returns False:
config = frozendict({
"debug": False
})
print(isinstance(config, dict))
frozendict implements the Mapping interface but does not inherit from dict.
Use the following approach when both types are acceptable:
from collections.abc import Mapping
print(isinstance(config, Mapping))
Assuming Nested Values Are Automatically Immutable
Consider:
config = frozendict({
"features": ["search", "reports"]
})
config["features"].append("analytics")
The list can still be modified.
Convert nested mutable objects into immutable equivalents when required.
Assuming Every frozendict Can Be Hashed
This example fails:
data = frozendict({
"items": [1, 2, 3]
})
print(hash(data))
The list is unhashable, so the complete mapping cannot be hashed.
Expecting MappingProxyType and frozendict to Behave Identically
MappingProxyType provides a read-only view of an existing dictionary.
frozendict creates an independent mapping containing the supplied entries.
Choose the appropriate type based on whether changes to the original dictionary should remain visible.
Trying to Update an Existing frozendict
This is not supported:
config = frozendict({
"debug": False
})
config.update({
"debug": True
})
Instead, create a new mapping:
updated_config = frozendict(
config | {"debug": True}
)
The original mapping remains unchanged.
Troubleshooting frozendict Issues
Problem | Possible Cause | Recommended Solution |
|---|
NameError: frozendict is not defined | Python version does not support the built-in type | Use Python 3.15 or a compatible alternative |
TypeError during item assignment | Attempting to modify immutable mapping entries | Create a new frozendict |
TypeError when calling hash() | One or more keys or values are unhashable | Use hashable values or avoid hashing the mapping |
isinstance(value, dict) returns False | frozendict is not a dict subclass | Check against collections.abc.Mapping |
Nested data changes unexpectedly | Mutable objects are stored inside the mapping | Recursively convert nested structures |
Changes to original dictionary are not visible | frozendict contains its own copied mapping | Use MappingProxyType when a live view is required |
JSON serialization fails | Unsupported nested objects or custom values | Check the contents and use an appropriate serialization strategy |
Conclusion
Python 3.15 introduces frozendict as a built-in immutable mapping through PEP 814. It provides dictionary-like access while preventing changes to mapping entries after creation.
One of its most useful features is hashability when all keys and values are hashable. This makes frozendict suitable for cache keys, sets, shared configuration, and other scenarios where ordinary dictionaries cannot be used.
It also supports common mapping operations, preserves insertion order, and integrates with several standard library modules.
However, developers should understand that frozendict provides shallow immutability. Mutable objects stored inside it can still change, and the type is not a subclass of dict.
For modern Python applications, frozendict offers a practical built-in option for managing stable, read-only mapping data without depending on third-party libraries.
Join the conversation! Your thoughts help the community grow.