Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Protocols

Pickle and Copy

Plain containers, concurrent maps and sets, and concurrent priority queues support pickle, copy.copy and copy.deepcopy. Use ConcurrentQueue.drain() to move FIFO contents into a list for copying or pickling.

  • The page size is part of the pickled state. Pickles made before page_size= existed load with page size 1024.
  • Hive and IdAllocator pickles keep generations and free slots, so ids stay valid across a round trip. A Hive rebuilds its free lists on load, so the slot the next insert takes can differ from the original. Restoring an older pickle revives ids removed since it was taken (see Hive).
  • Concurrent maps, sets and priority queues pickle a snapshot of their contents (see Python threads).

Loading a pickle whose page size the running build does not include raises ValueError (see page sizes).

Weak References

Every container class supports weakref.ref.

Subclassing

All container classes except the concurrent ones can be subclassed. Pickle and copy keep the subclass, its __dict__ and its __slots__ values (on 3.10 too, which lacks object.__getstate__).

Equality and Hashing

Plain containers compare by contents with ==. Concurrent containers compare by identity. Concurrent maps, sets and FIFO queues hash by identity. Plain containers and concurrent priority queues are unhashable. Lists and deques also support <, <=, >, >= against the same class, as list and deque do.

Collection ABCs

The package registers these classes with collections.abc for isinstance and issubclass checks. Virtual registration keeps each class’s native methods and return types.

ABCClasses
MutableMappingSparseMap, DirectMap, IdMap and their typed variants
MappingTyped concurrent sparse and direct maps
MutableSetSparseSet and BitSet
MutableSequencePagedList and its typed variants

Example

import pickle
import weakref

from paged_collections import SparseMap


class TaggedMap(SparseMap):
    __slots__ = ("tag",)


values = SparseMap([7, 2], [10, 20], page_size=256)
restored = pickle.loads(pickle.dumps(values))
print("page size =", restored.page_size)
print("items =", restored.items())
reference = weakref.ref(values)
print("weakref alive =", reference() is values)
del values
print("weakref cleared =", reference() is None)
tagged = TaggedMap([9], [30], page_size=256)
tagged.tag = "scores"
restored_tagged = pickle.loads(pickle.dumps(tagged))
print("subclass =", type(restored_tagged).__name__)
print("slot =", restored_tagged.tag)
print("subclass page size =", restored_tagged.page_size)
print("subclass items =", restored_tagged.items())
page size = 256
items = [(7, 10), (2, 20)]
weakref alive = True
weakref cleared = True
subclass = TaggedMap
slot = scores
subclass page size = 256
subclass items = [(9, 30)]