Live Dictionary Views and Snapshots

A live view observes changes to the same dictionary. A collected sequence of view items fixes the items observed at collection time.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a later insertion
  2. Audit nested state
  3. Compare a view and a copied sequence after one change
  4. Check how much of a snapshot is frozen

Trace a later insertion

Given a view of keys after inserting north, inserting south makes that same live keys view show both. A list built from the view before the insertion still has north only. Dictionary views preserve the separate roles of keys, values, and entries.

Audit nested state

A snapshot of items copies entry references. A later mutation of a list inside one stored value can still appear when inspecting the snapshot. Shallow copying explains why snapshot depth needs to match its promise.[1]

Compare a view and a copied sequence after one change

Starting from {"north": 4}, save keys = mapping.keys() and snapshot = tuple(mapping). Adding south makes the live keys view include it. The tuple still contains north alone. Which result is appropriate depends on when the reader is supposed to observe the mapping. A view is useful for inspecting current contents. A dated report typically needs a snapshot. See dictionary keys and values.

Check how much of a snapshot is frozen

Copying a mapping duplicates its outer entries but can preserve references to lists held as values. Mutating such a list may change earlier reports that retain those references. Capture immutable values when records must remain stable, or define a deeper snapshot with the necessary ownership semantics. Also avoid adding or removing keys while iterating a live view when the implementation does not support that change. See immutable record snapshots.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩