PYTHON

Create a Read-Only View of a Dictionary with MappingProxyType

Explore `types.MappingProxyType` in Python to create an immutable, read-only view of an existing dictionary, preventing accidental modifications while sharing data safely.

from types import MappingProxyType

# Original mutable dictionary
mutable_config = {
    'DATABASE_URL': 'postgres://user:pass@host:port/db',
    'DEBUG_MODE': False,
    'API_KEY': 'very_secret_key'
}

# Create a read-only view
immutable_config = MappingProxyType(mutable_config)

print("Original mutable config:", mutable_config)
print("Immutable config view:", immutable_config)

# Attempt to modify the immutable view (will raise TypeError)
try:
    immutable_config['DEBUG_MODE'] = True
except TypeError as e:
    print(f"Attempted to modify immutable view: {e}")

# The original dictionary can still be modified
mutable_config['DEBUG_MODE'] = True
print("Mutable config after change:", mutable_config)
print("Immutable view reflecting original change:", immutable_config)
How it works: `MappingProxyType` from the `types` module creates a read-only "view" of an existing dictionary. This means you can read from `immutable_config` just like a regular dictionary, but any attempts to modify it will result in a `TypeError`. Changes to the *original* `mutable_config` will still be reflected in the `immutable_config` view. This is incredibly useful for sharing configuration or data objects across different parts of an application where you want to prevent accidental modification, enforcing immutability for shared state.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs