Skip to content

How to change several fields at once

When you assign parcel.width and then parcel.height, that's two writes, and another process can read the box in between and see a new width with an old height. Reading two fields one after the other has the same problem. This guide shows how to write and read several fields together, so nobody sees a half-finished change.

1. Write them with update

update takes the fields by name and writes them all in one go:

from sharedbox import SharedBox


class Parcel(SharedBox, name="example-parcel"):
    width: int = 0
    height: int = 0


parcel = Parcel()
parcel.update(width=3, height=4)

A reader in any process then sees either all of the new values or none of them.

2. Handle a value that is refused

update checks every value before it writes any of them, so if one is wrong, nothing changes:

try:
    parcel.update(width=5, height="six")
except TypeError as error:
    print(error)  # Parcel.height expects int, got str
print(parcel.width)  # 3

3. Read them with snapshot

snapshot reads every field at the same moment and gives you them in a dict:

values = parcel.snapshot()
print(values)  # {'width': 3, 'height': 4}

4. Read the boxes a box refers to

A reference field shows up in a snapshot as a BoxRef, which says which box it points at. Pass follow=True to get the snapshot of that box instead:

class Order(SharedBox, name="example-order"):
    items: int = 0
    parcel: Parcel | None = None


order = Order(2, parcel)
print(order.snapshot())  # {'items': 2, 'parcel': BoxRef(...)}
print(order.snapshot(follow=True))  # {'items': 2, 'parcel': {'width': 3, 'height': 4}}

Each box is read at its own moment, though, so the nested snapshot isn't taken at the same instant as the outer one.

The whole script
"""The script of the guide "How to change several fields at once"."""

from sharedbox import SharedBox


class Parcel(SharedBox, name="example-parcel"):
    width: int = 0
    height: int = 0


parcel = Parcel()
parcel.update(width=3, height=4)

try:
    parcel.update(width=5, height="six")
except TypeError as error:
    print(error)  # Parcel.height expects int, got str
print(parcel.width)  # 3

values = parcel.snapshot()
print(values)  # {'width': 3, 'height': 4}


class Order(SharedBox, name="example-order"):
    items: int = 0
    parcel: Parcel | None = None


order = Order(2, parcel)
print(order.snapshot())  # {'items': 2, 'parcel': BoxRef(...)}
print(order.snapshot(follow=True))  # {'items': 2, 'parcel': {'width': 3, 'height': 4}}

order.close()
parcel.close()
Order.unlink()
Parcel.unlink()