Python 3.15 added frozendict, a built-in mapping that cannot be changed after creation. Think of a course settings card: code may read the course name and pass mark, but an accidental assignment should not change them. This small lesson shows the difference between reading a frozen mapping and making a new editable copy.
Create frozendict → Read values → Assignment raises TypeError → Copy to dict to edit
Check your Python version
Run python --version. This exact program requires Python 3.15 or newer. On an older interpreter, frozendict is not a built-in name. Use the official Python download page if you need the new version.
Try a frozen settings mapping
Save the following code as frozendict_demo.py, then run python frozendict_demo.py:
# Run with Python 3.15 or newer.
settings = frozendict({"course": "Python", "pass_mark": 40})
print(settings["course"])
print(settings["pass_mark"])
try:
settings["pass_mark"] = 50
except TypeError:
print("Original settings cannot be changed")
updated = dict(settings)
updated["pass_mark"] = 50
print(updated["pass_mark"])
Expected lines are Python, 40, Original settings cannot be changed, and 50. The last value comes from a separate normal dict; the frozen mapping still holds 40.
When is this useful?
- Pass settings to functions that should read them without replacing keys or values.
- Use a frozen mapping as a key only when every key and value inside it is hashable.
- Remember that this is shallow immutability: a mutable object stored inside can still change. For example, freezing a mapping that contains a list does not freeze that list.
A frozendict is not a subclass of dict. If a function should accept both kinds of mapping, check the collections.abc.Mapping interface instead of only dict.
Practice
- Add a
semestervalue and print it. - Make an editable copy with
dict(settings)and change the course name. Print both mappings. - Try a list value. Explain why the outer mapping stays frozen while the list can change.
Continue with the Python learning path. The official Python 3.15 release notes and frozendict reference cover the complete behavior.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.