Skip to content

How to store lists, sets and dicts

A field can hold a list, a tuple[T, ...], a set, a frozenset or a dict, or anything you annotate as Sequence, Set or Mapping from collections.abc. Because the box sets aside room for the field when it is created, you say up front how many elements it can hold at most.

1. Declare the field with a capacity in elements

On a collection, Capacity counts elements, not bytes. If the elements need a capacity of their own, such as text, put it on the element type inside:

from typing import Annotated

from sharedbox import Capacity, SharedBox, field

Tracking = Annotated[str, Capacity(16)]
Service = Annotated[str, Capacity(8)]


class Van(SharedBox, name="example-van"):
    parcels: Annotated[tuple[Tracking, ...], Capacity(8)] = ()
    services: Annotated[frozenset[Service], Capacity(4)] = frozenset()
    attempts: Annotated[dict[Tracking, int], Capacity(8)] = field(default_factory=dict)

The collection's own capacity can also go to field instead of the annotation, as it does for services, while an element's capacity stays on the element type.

Set elements and dict keys are read back into a new set or dict, so their type has to be hashable, meaning Python can use it as a set element or dict key. A list, set, dict, bytearray, TypedDict or record class that isn't frozen can't be a set element or a dict key, and the box class raises TypeError when you define it.

2. Write and read the collection

You assign and read a collection field like any other:

van = Van()
van.parcels = ("RR123", "RR456")
van.attempts = {"RR123": 3}
print(van.parcels, van.attempts)  # ('RR123', 'RR456') {'RR123': 3}

A read gives you a collection of the declared type. A field annotated as Sequence comes back as a list, a Set as a set and a Mapping as a dict, each a new object on every read. A tuple[T, ...] or a frozenset of values that can't be changed is the exception: you get the same object until the field is written (see When a read builds a new value). Order is kept: a set in the order you iterated it, a dict in insertion order.

3. Add an element

A collection you read is a copy, so appending to it changes nothing in the box. Build the new collection and assign it back:

van.parcels = (*van.parcels, "RR789")
print(len(van.parcels))  # 3

If you annotate the field as tuple[T, ...] or Sequence[T], a type checker will point out an append that would only change the copy. For a list of thousands of elements, where building every element on each read is what costs time, see How to store a large list, and for a large set or dict, How to store a large set or dict.

4. Handle a collection that is too large

Assigning more elements than the capacity raises ValueError, and the field keeps its old value:

try:
    van.services = frozenset({"express", "signed", "insured", "cold", "fragile"})
except ValueError as error:
    print(error)  # Van.services holds at most 4 elements; the value has 5
The whole script
"""The script of the guide "How to store lists, sets and dicts"."""

from typing import Annotated

from sharedbox import Capacity, SharedBox, field

Tracking = Annotated[str, Capacity(16)]
Service = Annotated[str, Capacity(8)]


class Van(SharedBox, name="example-van"):
    parcels: Annotated[tuple[Tracking, ...], Capacity(8)] = ()
    services: Annotated[frozenset[Service], Capacity(4)] = frozenset()
    attempts: Annotated[dict[Tracking, int], Capacity(8)] = field(default_factory=dict)



van = Van()
van.parcels = ("RR123", "RR456")
van.attempts = {"RR123": 3}
print(van.parcels, van.attempts)  # ('RR123', 'RR456') {'RR123': 3}

van.parcels = (*van.parcels, "RR789")
print(len(van.parcels))  # 3

try:
    van.services = frozenset({"express", "signed", "insured", "cold", "fragile"})
except ValueError as error:
    print(error)  # Van.services holds at most 4 elements; the value has 5

van.close()
Van.unlink()