Skip to content

Boxes

Name What it does
SharedBox a record whose annotated fields live in a named shared-memory segment
field sets the options of one field of a SharedBox class, as dataclasses.field does
fields returns one Field per field of a SharedBox subclass or box, in declaration order
Field options of one field of a SharedBox class, as field takes them
BoundedList a list value that keeps the stored form of a list field, so reading and writing it copies bytes instead of converting every element
BoundedSet a set value that keeps the stored form of a set field, so reading and writing it copies bytes and a lookup compares the stored bytes of one key
BoundedDict a dict value that keeps the stored form of a dict field, so reading and writing it copies bytes and a lookup compares the stored bytes of one key
Timed a value with its timestamp in nanoseconds, written in one go; Timed.now asks the write to stamp it
Attr an attribute: a field its owner publishes and every process reads, with a value and the time of its last publish, and through which other processes may send the owner requests
Setting an Attr that also holds a setpoint, which other processes ask the owner to change with set
attr declares an Attr or Setting field, which the box's constructor takes no value for
AttrValue what Attr.read returns
RequestFuture the answer to one request, waited on with result or await
RequestServer answers the requests of one attribute; Attr.serve returns it
Capacity maximum size of a field: bytes for text and bytes, elements for a collection. See capacity
segment_status says whether a box or stream exists under a name and whether its creator still runs
SegmentStatus what segment_status found: missing, running or creator_exited

SharedBox

SharedBox(*args: Any, metadata: object = None, **kwargs: Any)

Bases: Generic[M]

A record whose annotated fields live in a named shared-memory segment.

Subclass it and annotate the fields. Calling the subclass with the field values, as with a dataclass, creates the segment under the class's name and writes the values; create does the same under another name, so one class can describe several boxes, and attach opens an existing box from any thread or process. Every process that opens the segment reads and writes the same values.

A field is a public annotation with one of these types:

Annotation Stored as
bool, int, float, complex fixed-size numbers; a float field takes an int, and each takes numpy's scalars of its kind
numpy.int8 to numpy.uint64, numpy.float16 to numpy.float64, numpy.complex64, numpy.complex128, numpy.bool_ numbers at their own width, read back as that numpy type
numpy.datetime64 nanoseconds since 1970, read back in ns
Annotated[str, Capacity(n)], bytes, bytearray, Decimal at most n bytes
date, time, datetime, timedelta, UUID fixed-size values; times naive or with a fixed offset
an Enum, Flag or Literal the member's position, the bits, or the value's position
an optional X (Optional[X]), a union the member the value's type picks
a dataclass, NamedTuple, tuple, TypedDict, attrs class or msgspec.Struct its members
Annotated[list[T], Capacity(n)], and set, frozenset, dict, tuple[T, ...] at most n elements
Annotated[<array type>, Shape((...)), DType(...)] the array's elements

A SharedBox subclass, optional or not, makes a reference field, described below. Capacity sets n. A read returns a new value: changing a list, record or array read from a box changes only that copy. Names starting with _ and ClassVar annotations are not fields. Fields of a base class come first.

Fields are positional by default, in declaration order, as in a dataclass. Fields declared after a dataclasses.KW_ONLY annotation in the same class are keyword-only. A default is a plain class attribute or given with field, and is checked against the field's type and capacity when the class is defined. inspect.signature of the class gives its constructor's parameters; a default_factory default shows as <factory>.

Assigning a value of the wrong type raises TypeError, and a value that does not fit its field raises ValueError, or OverflowError for an int value out of range for its int, float or complex field; either way the stored value does not change. A bytes field takes bytes, bytearray and memoryview values. Assigning to a name that is not a field raises AttributeError, and so does deleting a field. A box has no __dict__: every subclass gets empty __slots__ unless it declares its own. Two boxes are equal only if they are the same object.

A dataclasses.InitVar[T] annotation declares a constructor argument that is not stored. It takes a position like a field and may have a default, as a class attribute or with field(default=...), but no default_factory and no init=False. It is not in the layout, the schema hash, fields, snapshot or events. An InitVar named like an inherited field removes that field from the subclass, as in dataclasses; reading or assigning that name on a box raises AttributeError.

__post_init__(self, *initvars) runs when the class is called and in create, after the values are written, with each InitVar value in declaration order. It may read and assign fields, reference fields included, and its writes go into the segment. It does not run for attach or unpickling. The box is published when __post_init__ returns, so no other process sees it before then. Until then its name is taken: creating another box under it raises SegmentExistsError, and attach, from any process or from __post_init__ itself, waits at most 1 s (the lock timeout, if shorter) and then raises SegmentNotFoundError. __sharedbox_box__ raises BufferError until then too. If __post_init__ raises, the box is closed and its name removed without ever being published, and the exception propagates.

The class statement takes these keywords:

  • name: the segment name of boxes made by calling the class. By default it is 16 hex digits of SHA-256 over the class's identity, so every process that imports the class uses the same name. It must be segments of [A-Za-z0-9_-] joined by :, at most 240 characters.
  • kw_only: make every field this class declares keyword-only. Inherited fields keep the setting of the class that declares them.
  • lock_timeout: seconds a read or write waits for a write in progress before it raises LockTimeoutError; 5.0 by default, finite and in (0, 86400].
  • identity: a non-empty string without |, by default the class's module.qualname, with __mp_main__ read as __main__. It enters the schema hash, and names the box when name is not given. A subclass does not inherit it. Two classes with the same identity and fields share a box, even when they live in different modules; a process whose class has another identity cannot attach it.
  • max_waiters: how many waiter slots the box has, 1 to 4096, 64 by default. Each box handle whose watch or events is in use holds one slot, counted across every process. A watcher that finds every slot taken logs a warning to the sharedbox logger and checks for changes once a second until a slot is free.
  • metadata_capacity: bytes of the box's metadata area, 0 for none or at least 24. The area takes 64 bytes, plus 32 per version, plus the capacity rounded up to a multiple of 8, and must not pass 2**32 - 1 bytes in all. A metadata document takes at most about a third of the capacity. By default a box created with metadata gets 65536, and any other box no area, so update with metadata on it raises MetadataFullError.
  • metadata_versions: how many metadata versions the box keeps at most, 2 to 65535, 64 by default.

Calling the class, or create, with the keyword metadata stores that value as the box's first metadata version; see metadata. A type checker takes the type of the metadata a box reads and writes from the class's base, as in class Motor(SharedBox[Info]). It accepts the keyword metadata only in create, and does not check its value.

A field annotated with a SharedBox subclass X, or with X | None (or Optional[X]), refers to another box, which keeps its own segment, lock and lifetime. The field stores the box's name, schema hash and create id. X is the class being defined or a class defined before it. A field X is never empty: assigning None raises TypeError, and reading it returns a box. A field X | None may hold None. The two give different schema hashes, so a class that declares one cannot attach a box created by a class that declares the other. Defaults work as for any field: = None, field(default=box) and field(default_factory=...). A default box is checked like an assigned one when the class is defined, a factory's result at each creation. The class keeps the handle given as field(default=box) for as long as the class exists; once that handle is closed, each creation that uses the default raises BoxClosedError.

Assigning a box to a reference field stores which box it is, under the outer box's lock. A box of X, of a subclass of X, or of any class with X's schema hash (the same identity and fields) is accepted; any other value raises TypeError, and a closed box raises BoxClosedError. The constructor and update check reference values the same way. Type checkers accept a box of X or of a subclass; a box of another class with X's schema hash needs a cast.

Reading a reference field attaches the box with its own class, which may be a subclass of X, and keeps that handle: later reads return the same object while the field refers to the same box. The class is found by the stored schema hash among the SharedBox classes this process has defined; of several with one hash, X itself is used when the hash is its own, else the class defined last, a subclass of X before any other. After another thread or process assigns another box, the next read attaches that one and closes the handle it kept. close on the outer box closes the handles its reads attached, and closing a returned box makes the next read attach it again. A read raises UnknownBoxClassError when this process has not imported the module that defines the box's class, and BrokenReferenceError when the box was removed, or removed and created again under the same name (also by another class), since it was assigned. A handle that already read the field keeps its own mapping of the box and goes on returning it. The outer box only points at the other box: closing or unlinking the outer box leaves it alone, and no write covers both boxes at once.

A box can be pickled, and copy.copy and copy.deepcopy do the same as a pickle round trip. The pickle holds the class, the segment name, the schema hash and the box's create id, a random number drawn when the box was created. Unpickling attaches a new handle: an independent box on the same data, which the receiving process closes. It reads reference fields from the segment like any other handle. A box pickled inside __post_init__ can be unpickled only once it is published. A child process started with fork uses the parent's box object, which keeps working after the fork.

Raises:

Type Description
TypeError

When the class is defined, for an annotation of another type, no fields or more than 256, a field or InitVar named like a SharedBox member (name, closed, close, unlink, update, snapshot, read_into, writing, locked, watch, events, force_unlock, create, attach, metadata, metadata_version, metadata_at), a field named follow, unfollow or nested, a default of the wrong type, a positional field without a default after one with a default, an InitVar in a class without __post_init__, a reference to a class that is not defined yet, __slots__ that name _segment or _values, or an identity that is not a non-empty string. When the class is called, for a missing, unknown or repeated value, a value of the wrong type, or metadata that update would refuse with TypeError.

ValueError

When the class is defined, for a name that is not segments of [A-Za-z0-9_-] joined by :, at most 240 characters, a lock_timeout, max_waiters, metadata_capacity or metadata_versions out of range, or a default that does not fit its field (any of the cases below). When the class is called, for metadata that update would refuse with ValueError, for any metadata when the class sets metadata_capacity=0, or for a metadata area that does not fit after the record in a box of at most 2**32 - 4096 bytes. When the class is called or a field is assigned, for a str, bytes or Decimal value longer than its capacity, a collection with more elements than its capacity, a tuple of the wrong length, an array of the wrong shape, a Literal field given another value, flag bits outside 0 to 2**64 - 1, a time or datetime whose UTC offset is not whole minutes of less than a day, or a time whose tzinfo gives no offset without a date.

OverflowError

When the class is defined or called, or a field is assigned, with an int value out of range for its int, float or complex field.

SegmentExistsError

When the class is called and the name is taken.

SchemaMismatchError

When a pickled box is loaded by a process whose class has different fields, or the box under that name was unlinked and created again since the pickle was made.

SegmentNotFoundError

When a pickled box is loaded after its segment is gone.

Notes

On Windows a lock wait ends on a timer tick, so lock_timeout can expire up to one tick late, 15.6 ms at the default timer resolution. The handle a class keeps for a field(default=box) default keeps that box's segment in existence on Windows, and so does the mapping a handle keeps of a box it read through a reference field: other handles can still attach it.

name property

name: str

Name of the segment; pass it to attach in another process.

closed property

closed: bool

True once close was called on this box.

metadata property

metadata: M | None

The value of the box's newest metadata version, or None if it has none.

Metadata is a document stored beside the fields, such as the units or calibration the values were taken with. Adding a version with update keeps the earlier ones until the box reclaims them for newer ones, and metadata_at reads them until then. A mapping reads back as a frozendict and a list as a tuple, nested the same way. Each box object decodes a version once and keeps the 32 it used last.

Raises:

Type Description
BoxClosedError

If the box is closed.

metadata_version property

metadata_version: int

The number of the box's newest metadata version, 0 if it has none.

Raises:

Type Description
BoxClosedError

If the box is closed.

events property

events: BoxEvents

One psygnal signal per field, emitted as (new, old) when any thread or process changes it.

A BoxEvents group: box.events.<field>.connect(cb) listens to one field and box.events.connect(cb) to all of them. The group's signal metadata is emitted with the new version number when any process adds metadata to the box.

Unlike the callbacks of a local evented dataclass, these run on the box's watcher thread; connect with thread="main" and call psygnal.emit_queued() to run them on the main thread instead. Closing the box delivers writes the watcher thread had not seen yet, so callbacks may run once on the thread that calls close. A box that is garbage collected drops them.

If several writes happen between two checks by the watcher thread, only one emission happens, with the latest value; old is the value from the last emission. A write that leaves the value unchanged emits nothing. For the first emission of a field, old is the value the field held when events was first accessed.

A callback that raises is logged to the sharedbox logger. Callbacks connected before it on the same signal already ran; callbacks connected after it do not run for that write. Other fields still emit. The watcher thread also serves this box's watch iterators, so a slow callback delays them. A callback that refers to the box, such as a lambda that reads a field, keeps the box alive until close.

A field named like an attribute of psygnal's SignalGroup (connect, disconnect, all, signals, block and others) makes psygnal warn when the class is defined, and box.events.<name> then returns that attribute; box.events["<name>"] returns the field's signal.

psygnal's blocked, paused, throttled, debounced and psygnal.qt.start_emitting_from_queue work on these signals. A signal that is blocked drops its emissions in this process, and changes made while it is blocked are not emitted later.

A reference field's signal is emitted when the field is assigned another box or emptied, with a BoxRef or None as new and old. Changes inside the box it refers to are emitted by that box's own events, and by this group once follow forwards them.

An attr field's signal is emitted with an AttrValue as new and old when its owner publishes, never for a request. An attr whose type is None has no signal: reading it raises TypeError.

A child process created with fork while a callback is running inherits that signal's lock as held, and hangs the first time it connects to, disconnects from or emits that signal.

unlink = Unlink()

Remove the segment's name, so no later process can attach to it.

Mailbox.unlink(name=None) on the class removes name, by default the class's name; box.unlink() on a box removes the name of its segment. Boxes already open keep working. On Linux, later attach calls fail. On Windows this does nothing; the segment goes away with its last handle.

Raises:

Type Description
ValueError

If name is not segments of [A-Za-z0-9_-] joined by :, at most 240 characters.

SegmentNotFoundError

On Linux, if no segment has that name.

create classmethod

create(name: str, /, *args: Any, metadata: object = None, **kwargs: Any) -> Self

Create a box under name instead of the class's name.

Takes the field values and the keyword metadata, and runs __post_init__, as calling the class does.

Raises:

Type Description
SegmentExistsError

If the name is taken.

ValueError

If name is not segments of [A-Za-z0-9_-] joined by :, at most 240 characters.

attach classmethod

attach(name: str | None = None) -> Self

Open the box called name, by default the one named after this class.

__post_init__ does not run.

Raises:

Type Description
SegmentNotFoundError

If no segment has that name, or the shared memory under it does not become a box within 1 s (the lock timeout, if shorter).

KindMismatchError

If the name holds a segment of another kind.

SchemaMismatchError

If the segment was created by a different class or a different version of this class, uses another major version of the segment layout, has a field of a kind this version cannot read, or is not a segment this version of sharedbox knows.

ValueError

If name is not segments of [A-Za-z0-9_-] joined by :, at most 240 characters.

metadata_at

metadata_at(version: int) -> M

Return the value of metadata version version.

Each box object decodes a version once and keeps the 32 it used last.

Raises:

Type Description
MetadataGoneError

If the box no longer holds that version, or never did.

BoxClosedError

If the box is closed.

update

update(*, metadata: M | None = None, **values: Any) -> None

Write several fields under one lock; a reader sees all of the new values or none.

Every value is checked before any is written, so an update that raises changes nothing. A reference field takes a box or None, checked as when it is assigned.

With metadata, the same lock also adds the value as the box's next metadata version, and no reader sees the fields without it. The value is None, a bool, an int from -2**64 to 2**64 - 1, a float, a str, bytes, a mapping with str keys, or a list or tuple, nested up to 32 levels. The metadata signal of events is emitted before the signals of the fields, in every process that listens to them. The oldest versions are reclaimed once the box holds metadata_versions of them, or needs their room in its metadata area. metadata=None adds no version.

Raises:

Type Description
TypeError

If a name is not a field or a value has the wrong type, or the metadata holds another type or a mapping key that is not a str.

ValueError

If a str or bytes value is longer than its capacity, or an int of the metadata is out of range, its nesting is deeper than 32 levels, or its document is longer than the metadata area takes, about a third of the class's metadata_capacity.

MetadataFullError

With metadata, if the box has no metadata area: its class sets no metadata_capacity and it was created without metadata.

LockTimeoutError

If another writer holds the lock longer than the lock timeout.

BoxClosedError

If the box is closed.

snapshot

snapshot(*, follow: bool = False) -> dict[str, Any]

Return every field's value, with this box read at one point in time.

A reference field gives a BoxRef, or None when it is empty.

Parameters:

Name Type Description Default
follow bool

Replace each reference with the snapshot of the box it refers to, itself taken with follow. Each box is read at its own moment, not together with the others. A box this call has already read stays a BoxRef, also when a second field refers to it, so a loop of references (a box that refers to itself, or A to B and B to A) ends.

False

Raises:

Type Description
BrokenReferenceError

With follow, if a box referred to no longer exists or was created again.

UnknownBoxClassError

With follow, if no class defined in this process has the schema hash of a box referred to.

read_into

read_into(field: str, out: A) -> A

Copy an array field into out and return out.

The copy holds one complete write, as a read does, but goes into memory the caller already has, so nothing is allocated.

Parameters:

Name Type Description Default
out A

A writable, C-contiguous array in CPU memory with the field's DType and Shape. Its contents are unspecified if the call raises.

required

Raises:

Type Description
TypeError

If the field is not an array field, or out is not a writable, C-contiguous array in CPU memory.

ValueError

If the box has no such field, or out has another dtype or shape.

LockTimeoutError

If another writer holds the lock longer than the lock timeout.

BoxClosedError

If the box is closed.

writing

writing(field: str, shape: tuple[int, ...] | None = None) -> Generator[Any, None, None]

Hold the box's write lock and yield the array field to fill in place.

The block gets an array of the field's declared type that views the field in shared memory and holds its current value. For a MaxShape field the array has the stored shape, or shape when given, which is stored under the same lock, so a watcher never sees a new shape with old data. When the view is larger than the stored shape, the part past the stored elements, counted in C order, holds what an earlier and larger write left, so fill all of the view. Leaving the block releases the lock, counts the write and wakes watchers, also when the block raises, since the bytes have already changed. While the block runs, reads and writes of the box in every process wait for the lock, so keep it short. Writing a field of this box inside the block waits on that same lock and raises LockTimeoutError. The array keeps its own mapping, so using it after the box is closed cannot crash, but writing to it after the block takes no lock and tells no one.

Parameters:

Name Type Description Default
shape tuple[int, ...] | None

The shape to store, for a MaxShape field.

None

Raises:

Type Description
TypeError

If the field is not an array field, or shape is given for a field with a fixed Shape.

ValueError

If the box has no such field, or shape has another number of dimensions than the field's MaxShape or a dimension beyond it.

LockTimeoutError

If another writer holds the lock longer than the lock timeout.

BoxClosedError

If the box is closed.

locked

locked() -> Generator[Self, None, None]

Hold the box's write lock and yield an object whose fields are read and written under it.

Use it for a write computed from the box's values, such as b.count += 1, which plain assignment can lose between processes that read the old value at the same time. See Change a field from several processes.

The object has the box's fields, and update and snapshot without their metadata and follow options. A read gives the value the block last wrote to the field, or the field's value when it wrote none. Leaving the block counts one write for each field it wrote and wakes watchers, which see only the last value of each field. If the block raises, including KeyboardInterrupt, every field goes back to what it held before the block, nothing is counted, and no watcher sees a value; the exception propagates.

While the block runs, reads and writes of the box in every other process wait for the lock, so keep it short. In the thread that holds it, the box itself refuses every read and write with RuntimeError, and the object refuses the box's other methods (close, watch, events, writing, locked and the rest) with TypeError; so does an attr field. The object works in the thread that entered the block, until the block ends. Its metadata, metadata_version, name and closed read the box as the box does.

Raises:

Type Description
RuntimeError

If the thread already holds a locked() block of this box; from the object, if the block has ended or another thread uses it.

LockTimeoutError

If another writer holds the lock longer than the lock timeout.

BoxClosedError

If the box is closed.

watch

watch(field: str) -> FieldWatch[Any]

Return a FieldWatch over the values written to field from now on.

A reference field yields a BoxRef or None. An attr field yields an AttrValue on each publish, and nothing for a request.

Raises:

Type Description
ValueError

If the class has no field field.

TypeError

If field is an attr field whose type is None.

force_unlock

force_unlock() -> None

Release a write lock left behind by a process that died while writing.

Reads and writes that wait on such a lock raise LockTimeoutError, whose message names the process that holds it. This does not check whether the process that held the lock is still running: releasing the lock of a writer that is still running lets other reads and writes run while its write is half done.

__sharedbox_box__

__sharedbox_box__(max_version: tuple[int, int] | None = None, **kwargs: Any) -> CapsuleType

Return a "sharedbox_box" capsule holding a handle with its own mapping of the segment.

Python code does not call it; an extension that accepts a box does. The capsule holds a pointer to an sbx_handle, declared in sharedbox/sharedbox_c.h. The handle's mapping is made from the box's OS handle, so closing or unlinking the box does not affect it. A consumer takes the handle with sharedbox::handle::from_capsule (C++) or sbx_import (C), renames the capsule "used_sharedbox_box", compares the box's schema hash with the one it expects, and destroys (C++) or releases (C) the handle itself. A capsule that is never taken releases the handle when it is garbage collected. Releasing touches no Python objects and does not need the GIL, so it may run on any thread and after interpreter shutdown.

Parameters:

Name Type Description Default
max_version tuple[int, int] | None

The (major, minor) layout version the caller supports; None means the box's own.

None

Raises:

Type Description
BufferError

If the major version of max_version differs from the box's layout, if its minor version is older than the oldest whose readers open this box, or if called from __post_init__, before the box is published.

NotImplementedError

If any other keyword is given.

Notes

On Windows the segment stays in existence while a handle is held.

close

close() -> None

Detach from the segment; other boxes on it keep working and the data stays.

Use unlink to remove it. Also stops this box's watcher thread, closes every box this handle attached to read a reference field, and stops all forwarding started through its events. Later reads and writes raise BoxClosedError. Calling it again does nothing. Leaving a with block calls it.

Called on a box's watcher thread, from an event callback, it does not wait for the watcher threads of the boxes it closes, and drops the writes those threads had not seen yet.

A thread of this process that waits for the box's lock stops waiting within a millisecond and raises BoxClosedError, so close does not wait for the class's lock_timeout to pass.

A box that is garbage collected is closed. Forwarding it started keeps running until its events group and every group follow returned are garbage collected too, which happens only when the cycle collector runs.

field

field(*, default: Any = MISSING, default_factory: Callable[[], Any] | Any = MISSING, init: bool = True, repr: bool = True, kw_only: bool | Any = MISSING, metadata: Mapping[Any, Any] | None = None, doc: str | None = None) -> Any

Set the options of one field of a SharedBox class, as dataclasses.field does.

A plain class attribute is still the field's default. There is no compare or hash option: two boxes are equal only if they are the same object. A field with neither default nor default_factory is required. A default is checked against the field's type and capacity when the class is defined, and a factory's result when a box is created; both raise what assigning the value raises, except that an array default of another shape than the field's Shape raises TypeError when the class is defined. Values are copied into the segment, and only the stored types exist: no lists, dicts or other objects.

A positional field without a default cannot follow one with a default; a field with default or default_factory counts as having one, and init=False fields take no position and are not counted.

Whether a field is keyword-only is fixed by the class that declares it, through its kw_only class keyword, a dataclasses.KW_ONLY among its own annotations, or kw_only here. A subclass keeps each inherited field's setting: its own kw_only=True affects only its own fields, and the fields of a kw_only base stay keyword-only in a subclass without the keyword.

A subclass that declares an inherited field again, with an annotation, gives it default options, as in dataclasses. An annotation without a value keeps only a plain inherited default: the other options go back to their defaults, and a field whose base gave it a default_factory becomes required. The same holds for an InitVar declared over an inherited field.

Parameters:

Name Type Description Default
default_factory Callable[[], Any] | Any

Called once per creation that is given no value for the field. The result is stored like any other value, so the box never keeps the object the factory returned.

MISSING
init bool

False leaves the field out of the constructor; the field then needs default or default_factory.

True
repr bool

False leaves the field out of repr() of a box.

True
kw_only bool | Any

Make this field keyword-only or not, whatever the kw_only class keyword and KW_ONLY say.

MISSING
metadata Mapping[Any, Any] | None

Kept in Python as a read-only mapping, never stored in the segment.

None
doc str | None

Kept in Python, never stored in the segment.

None

Raises:

Type Description
ValueError

If both default and default_factory are given.

TypeError

When the class is defined, for field() on a name that is not a field (a name starting with _, a ClassVar), field() without an annotation, init=False without a default, or a subclass that sets a plain class attribute, without an annotation, on the name of an inherited field.

fields

fields(class_or_box: type[SharedBox] | SharedBox) -> tuple[Field, ...]

Return one Field per field of a SharedBox subclass or box, in declaration order.

InitVar annotations are left out. This is how a field's metadata and doc are read.

Raises:

Type Description
TypeError

If the argument is neither a subclass of SharedBox nor one of its boxes.

Field dataclass

Options of one field of a SharedBox class, as field takes them.

field and attr make one and fields returns them; a Field is not built directly. It is read-only, and two are equal only if they are the same object, as with dataclasses.Field.

type instance-attribute

type: Any

The evaluated annotation, with Annotated extras kept.

default instance-attribute

default: Any

dataclasses.MISSING when there is none.

default_factory instance-attribute

default_factory: Any

A function of no arguments, or dataclasses.MISSING.

init instance-attribute

init: bool

False if the constructor takes no value for the field.

repr instance-attribute

repr: bool

False if repr() of a box leaves the field out.

kw_only instance-attribute

kw_only: Any

True if the constructor takes the value by keyword only; dataclasses.MISSING until the class is created.

metadata instance-attribute

metadata: Mapping[Any, Any]

Read-only; kept in Python, never stored in the segment.

doc instance-attribute

doc: str | None

Kept in Python, never stored in the segment.

is_attr class-attribute instance-attribute

is_attr: bool = False

True for a field declared with attr.

Timed

Bases: NamedTuple, Generic[T]

A value with a timestamp in nanoseconds since the Unix epoch.

A box field or stream item annotated Timed[T] stores value as a T followed by timestamp_ns. The timestamp -2**63 is reserved: a box write replaces it with the system clock once it holds the box's lock, so the stored timestamps follow the order of the writes unless the clock is set back, and a stream send replaces it before it publishes the item. No read returns it.

timestamp property

timestamp: float

The timestamp in seconds since the Unix epoch.

now classmethod

now(value: T) -> Timed[T]

Return value with the mark that asks the write to stamp it with the clock.

Attr

Bases: Generic[T, P]

A box field that its owner publishes and every process reads.

Annotate a field Attr[T] and declare it with attr. T is the type of its value, or None for an attribute without one. The field holds no value that a process assigns: reading it from a box gives the Attr bound to that box, the same object every time, so an Attr is not built directly.

An attribute stores the time of each publish of its value. It starts with its value at the zero of T, or at its default, and with a timestamp of 0. T may be anything a record member may be, except a Timed, an Attr or a reference to a box.

An attribute with argument types P, or with a T of None, takes requests: calling it sends one, and serve answers them. A Setting also has a setpoint and takes its requests through set. Answering a request publishes nothing.

value property

value: T

The value, as of the last publish.

Raises:

Type Description
TypeError

If the attribute has no value.

BoxClosedError

If the box is closed.

timestamp_ns property

timestamp_ns: int

The time of the last publish of the value, in nanoseconds since the Unix epoch.

Raises:

Type Description
TypeError

If the attribute has no value.

BoxClosedError

If the box is closed.

read

read() -> AttrValue[T]

Return the value and its timestamp, with the setpoint of a Setting, from one write.

Raises:

Type Description
TypeError

If the attribute has no value.

BoxClosedError

If the box is closed.

publish

publish(*, value: T = UNSET, timestamp_ns: SupportsIndex = UNSET) -> None

Write the value, and its time if given, in one write.

A value given without timestamp_ns is stamped with the time of the write, and so is one given -2**63.

Raises:

Type Description
TypeError

If nothing is given, timestamp_ns comes without value, a part is not one the attribute has, or a part has the wrong type.

ValueError

If a part does not fit its type.

OverflowError

If timestamp_ns does not fit 64 bits.

BoxClosedError

If the box is closed.

__call__

__call__(*args: args, **kwargs: kwargs) -> RequestFuture[T]

Send a request with args and return the future of its answer.

The request is sent whether or not anyone waits for the future, and replaces an earlier one the server has not taken yet.

Raises:

Type Description
TypeError

If the attribute takes no requests or is a Setting, an argument is given by keyword, or the arguments do not match its argument types.

ValueError

If an argument does not fit its type.

OverflowError

If a number is out of the range of its type.

BoxClosedError

If the box is closed.

serve

serve(handler: Callable[P, Awaitable[T]]) -> RequestServer
serve(handler: Callable[P, T]) -> RequestServer
serve(handler: Callable[..., Any]) -> RequestServer

Answer the attribute's requests with handler until the server is stopped or the box closed.

A sync handler runs on a thread of its own; an async one runs as a task on the event loop running at this call. The handler handles one request at a time, and of the requests sent meanwhile only the newest is handled next. Its return value is the answer; an exception it raises is logged to the sharedbox logger and reaches the caller as RequestError; RequestRefused reaches the caller the same way and is not logged. A Setting's handler receives the value given to set.

Raises:

Type Description
TypeError

If the attribute takes no requests.

AlreadyServedError

If a live process serves the field already, this one included.

RuntimeError

If handler is async and no event loop is running.

BoxClosedError

If the box is closed.

Setting

Bases: Attr[T, []]

An attribute with a setpoint, which other processes ask its owner to change.

Annotate a field Setting[T] and declare it with attr. A Setting is an Attr that also holds a setpoint of type T; its requests carry the new value. Reading the field from a box gives the Setting bound to that box, so a Setting is not built directly.

setpoint property

setpoint: T

The setpoint, as of the last publish.

Raises:

Type Description
BoxClosedError

If the box is closed.

publish

publish(*, value: T = UNSET, setpoint: T = UNSET, timestamp_ns: SupportsIndex = UNSET) -> None

Write the parts given in one write, so a reader never sees parts of different publishes together.

A value given without timestamp_ns is stamped with the time of the write, and so is one given -2**63. A setpoint alone keeps the value and its time.

Raises:

Type Description
TypeError

If nothing is given, timestamp_ns comes without value, or a part has the wrong type.

ValueError

If a part does not fit its type.

OverflowError

If timestamp_ns does not fit 64 bits.

BoxClosedError

If the box is closed.

set

set(value: T) -> RequestFuture[T]

Send value as the one argument of a request, and return the future of its answer.

The handler given to serve receives value and decides what to publish.

Raises:

Type Description
TypeError

If value does not have the attribute's type.

ValueError

If value does not fit its type.

BoxClosedError

If the box is closed.

serve

serve(handler: Callable[[T], Awaitable[T]]) -> RequestServer
serve(handler: Callable[[T], T]) -> RequestServer
serve(handler: Callable[..., Any]) -> RequestServer

Answer the setting's requests with handler until the server is stopped or the box closed.

handler receives the value given to set and is served as Attr.serve describes.

Raises:

Type Description
AlreadyServedError

If a live process serves the field already, this one included.

RuntimeError

If handler is async and no event loop is running.

BoxClosedError

If the box is closed.

attr

attr(*, init: Literal[False] = False, default: Any = MISSING, metadata: Mapping[Any, Any] | None = None, doc: str | None = None) -> Any

Declare an Attr or Setting field of a SharedBox class.

Write exposure: Setting[float] = attr(default=0.01). An attribute is published by its owner, so the box's constructor takes no value for it, for type checkers too.

Parameters:

Name Type Description Default
init Literal[False]

Leave it out. Type checkers read its default.

False
default Any

The starting value, and the starting setpoint. Without it the value starts at the zero of its type, which a record has none of.

MISSING
metadata Mapping[Any, Any] | None

As field takes them.

None
doc Mapping[Any, Any] | None

As field takes them.

None

AttrValue

Bases: TypedDict, Generic[T]

What Attr.read returns: the parts of an attribute, read together.

setpoint instance-attribute

setpoint: NotRequired[T]

Present when read from a Setting.

timestamp_ns instance-attribute

timestamp_ns: int

The time of the last publish of the value, in nanoseconds since the Unix epoch.

RequestFuture

Bases: Future[R]

The answer to one request sent through an Attr field.

Calling the attribute, or its set, returns it; it is not built directly.

A concurrent.futures.Future, so .result(timeout) waits in any thread, and it can be awaited in a running event loop. The box's watcher thread completes it, and closing the box cancels it. Cancelling it stops the wait only: the request stays sent.

cancel

cancel() -> bool

Stop waiting; False if the future already has its answer, True otherwise.

result

result(timeout: float | None = None) -> R

Block until the answer arrives and return the handler's result.

Raises:

Type Description
TimeoutError

If no answer arrived within timeout seconds.

RequestError

If the request failed; see its subclasses.

CancelledError

If the future was cancelled, or the box closed.

RuntimeError

If the answer has not arrived and this is called from a callback of the same box's events: that thread is the one that delivers the answer.

RequestServer

Answers the requests of one attr field.

Attr.serve returns it; it is not built directly.

stop

stop() -> None

Stop answering and free the field for another server.

A sync handler that is running is waited for, unless this is called from the handler itself or from a callback on the box's watcher thread. For an async handler, cancelling its task is requested of the event loop, which runs the cancellation after this returns. A request taken and not answered yet fails with "the server stopped". Calling it again does nothing, unless the first call raised: then the field is still claimed and this call frees it.

Raises:

Type Description
RuntimeError

If called inside a locked() block of the box. The server has stopped answering; call stop again after the block.

LockTimeoutError

If the box's write lock stayed held. Call stop again once it is free.

BoundedList

BoundedList(element: type[T], values: Iterable[T] = (), /, *, capacity: int)
BoundedList(values: Iterable[T] = (), *, capacity: int)
BoundedList(element: object, values: Iterable[Any], /, *, capacity: int)
BoundedList(values: Any = (), *args: Any, capacity: int)

Bases: NativeCollection[T]

A list of at most a field's capacity of elements, held as the field stores them.

Declared as Annotated[BoundedList[T], Capacity(n)], it is stored as list[T] is, and a read returns one. Indexing decodes or encodes one element, and setting an element checks the value as a write to the field would. A change that would leave more elements than the capacity raises ValueError and leaves the value as it was.

BoundedList(int, values, capacity=n) or BoundedList[int](values, capacity=n) builds one outside a box. Copies, slices, + and * keep the class, the element type and the capacity, and a pickled value is rebuilt from them and its bytes.

A subclass is declared and read back the same way, generic as class MyList(BoundedList[T]) used as MyList[float], or with its element type fixed as class Points(BoundedList[float]). A read from a box calls neither __new__ nor __init__. copy.copy, copy.deepcopy and pickling keep a subclass's attributes, as for a list subclass, while slices, + and * return the class without them.

A list of int, float, bool, complex or NumPy integer, float, complex or bool_ elements supports the buffer protocol: np.asarray(value) and memoryview(value) share its elements without decoding them, read only for bool and bool_. While such a view exists, a change of length raises BufferError.

Do nothing; __new__ has built the value.

Raises:

Type Description
TypeError

If there are positional arguments beyond the values and the type.

capacity property

capacity: int

The most elements the value can hold.

insert

insert(index: SupportsIndex, value: _T) -> None

Insert an element before index, clamped to the value as list.insert clamps it.

Raises:

Type Description
OverflowError

If index does not fit a C Py_ssize_t.

TypeError

If the element is not of the field's element type.

ValueError

If the element does not fit, or the value already holds its capacity of elements.

append

append(value: _T) -> None

Add an element at the end.

Raises:

Type Description
TypeError

If the element is not of the field's element type.

ValueError

If the element does not fit, or the value already holds its capacity of elements.

extend

extend(values: Iterable[_T]) -> None

Append the elements of an iterable, all of them or none.

Raises:

Type Description
TypeError

If an element is not of the field's element type.

ValueError

If an element does not fit, or the value would hold more elements than its capacity.

pop

pop(index: SupportsIndex = -1) -> _T

Remove the element at index, the last by default, and return it.

An element that fails to decode stays in the value.

Raises:

Type Description
OverflowError

If index does not fit a C Py_ssize_t.

IndexError

If the value is empty or has no such element.

remove

remove(value: _T) -> None

Remove the first element equal to value.

Raises:

Type Description
ValueError

If no element is equal to value.

index

index(value: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize) -> int

Return the position of the first element equal to value from start to stop.

Raises:

Type Description
ValueError

If no element in that range is equal to value.

count

count(value: _T) -> int

Return the number of elements equal to value.

reverse

reverse() -> None

Reverse the elements in place without decoding them.

clear

clear() -> None

Remove every element.

copy

copy() -> Self

Return a new value of the same element type and capacity holding the same elements.

The slots are copied without decoding an element.

BoundedSet

BoundedSet(element: type[T], values: Iterable[T] = (), /, *, capacity: int)
BoundedSet(values: Iterable[T] = (), *, capacity: int)
BoundedSet(element: object, values: Iterable[Any], /, *, capacity: int)
BoundedSet(values: Any = (), *args: Any, capacity: int)

Bases: NativeSet[T]

A set of at most a field's capacity of elements, held as the field stores them.

Declared as Annotated[BoundedSet[T], Capacity(n)], it is stored as set[T] is, and a read returns one. It iterates in the order its elements are stored, which may differ from a builtin set's.

Elements are compared by their stored bytes, all of them but the fold of a naive datetime or time, so a declaration refuses an element type whose equal values could be stored differently: a Decimal, a frozenset, a union whose members can hold equal values, such as int | float or a StrEnum and str, a Literal of two equal values such as Literal[1, True], a record whose equality skips a member, as field(compare=False) does, and a float, complex or time type inside a union or a tuple[T, ...]. For the same reason, a set of a record class with its own __eq__ may hold two elements that class counts as equal.

Adding a nan, a NaT, or an aware datetime or time raises ValueError, and -0.0 is stored as 0.0. A naive datetime keeps the fold it was added with, and is the same element as that time at the other fold. A value that cannot be stored as an element is in no set: in returns False and remove raises KeyError.

The operators |, &, - and ^ and their in-place forms take any set and return a value of this class and capacity, on either side of the operator, and the comparisons take any set. &, value - other and the comparisons treat an element of the other set that this one cannot hold as absent; |, ^ and other - value raise the error that adding it would.

A subclass is declared and read back the same way, generic as class MySet(BoundedSet[T]) used as MySet[int], or with its element type fixed as class Tags(BoundedSet[int]). A read from a box calls neither __new__ nor __init__. copy.copy, copy.deepcopy and pickling keep a subclass's attributes, as for a set subclass.

BoundedSet(int, values, capacity=n) or BoundedSet[int](values, capacity=n) builds one outside a box.

Do nothing; __new__ has built the value.

Raises:

Type Description
TypeError

If there are positional arguments beyond the values and the type.

capacity property

capacity: int

The most elements the value can hold.

add

add(value: _T) -> None

Add value unless the set holds it.

Raises:

Type Description
TypeError

If value is not of the field's element type.

ValueError

If value does not fit, is a key the field refuses (a nan, a NaT, an aware datetime or time), or the set is full.

discard

discard(value: _T) -> None

Remove value if the set holds it.

remove

remove(value: _T) -> None

Remove value.

Raises:

Type Description
KeyError

If the set does not hold value.

pop

pop() -> _T

Remove the element in the last slot and return it.

An element that fails to decode stays in the value.

Raises:

Type Description
KeyError

If the value is empty.

clear

clear() -> None

Remove every element.

update

update(*iterables: Iterable[_T]) -> None

Add the elements of every iterable, all of them or none.

Raises:

Type Description
TypeError

If an element is not of the field's element type, or an iterable is a value that was never built.

ValueError

As add raises it, or if the distinct new elements would pass the capacity.

isdisjoint

isdisjoint(other: Iterable[object]) -> bool

Return whether this set holds none of the elements of other.

Raises:

Type Description
TypeError

If other is a value that was never built.

copy

copy() -> Self

Return a new value of the same element type and capacity holding the same elements.

The slots are copied without decoding an element.

BoundedDict

BoundedDict(key: type[K], value: type[V], values: Mapping[K, V] | Iterable[tuple[K, V]] = (), /, *, capacity: int)
BoundedDict(values: Mapping[K, V] | Iterable[tuple[K, V]] = (), *, capacity: int)
BoundedDict(key: object, value: object, values: Mapping[Any, Any] | Iterable[tuple[Any, Any]], /, *, capacity: int)
BoundedDict(values: Any = (), *args: Any, capacity: int)

Bases: NativeDict[K, V]

A dict of at most a field's capacity of items, held as the field stores them.

Declared as Annotated[BoundedDict[K, V], Capacity(n)], it is stored as dict[K, V] is, and a read returns one. It keeps its items in insertion order, as a dict does. A change that would leave more keys than the capacity raises ValueError and leaves the value as it was. | takes any mapping on either side and returns a value of this class and capacity.

Keys follow the rules of BoundedSet elements: they are compared by their stored bytes, so a declaration refuses the same key types, and a nan, a NaT, or an aware datetime or time key raises ValueError. A key that cannot be stored is in no dict: in returns False and d[key] raises KeyError. Values may be of any type a dict field takes, and == compares them as dict does.

A subclass is declared and read back the same way, generic as class MyDict(BoundedDict[K, V]) used as MyDict[int, float], or with its types fixed as class Weights(BoundedDict[int, float]). A read from a box calls neither __new__ nor __init__. copy.copy, copy.deepcopy and pickling keep a subclass's attributes, as for a dict subclass.

BoundedDict(int, float, values, capacity=n) or BoundedDict[int, float](values, capacity=n) builds one outside a box.

Do nothing; __new__ has built the value.

Raises:

Type Description
TypeError

If there are positional arguments beyond the values and the types.

capacity property

capacity: int

The most items the value can hold.

popitem

popitem() -> tuple[_K, _V]

Remove the last item and return it.

An item that fails to decode stays in the value.

Raises:

Type Description
KeyError

If the value is empty.

clear

clear() -> None

Remove every item.

copy

copy() -> Self

Return a new value of the same types and capacity holding the same items.

The slots are copied without decoding a key or value.

Capacity dataclass

Capacity(size: int)

Maximum size of a field: bytes for str, bytes, bytearray and Decimal, elements for a collection.

It goes in the annotation, as in Annotated[str, Capacity(32)] or Annotated[list[int], Capacity(16)], and allows 1 to 1048576 (1 Mi).

Raises:

Type Description
TypeError

If size is not an int.

ValueError

If size is not between 1 and 1 Mi.

size instance-attribute

size: int

Bytes for text and bytes, not characters: a UTF-8 character can take up to 4 bytes; elements for a collection.

segment_status

segment_status(name: str) -> SegmentStatus

Say whether a box or stream exists under name and whether its creator still runs.

A segment that another process is creating is waited for up to 1 s, and one still not published then counts as missing.

Raises:

Type Description
ValueError

If name is not segments of [A-Za-z0-9_-] joined by :, at most 240 characters.

SchemaMismatchError

If the segment uses a core version of the layout this sharedbox cannot read.

OSError

If the operating system refuses to open the segment, such as one of another user.

Notes

On Windows a segment goes away with its last handle, so CREATOR_EXITED appears only while another process still holds the segment open.

SegmentStatus

Bases: StrEnum

What segment_status found under a name.

MISSING class-attribute instance-attribute

MISSING = 'missing'

No box or stream is published under the name.

RUNNING class-attribute instance-attribute

RUNNING = 'running'

A box or stream is published under the name, and the process that created it still runs or cannot be judged from this process, such as one in another pid namespace.

CREATOR_EXITED class-attribute instance-attribute

CREATOR_EXITED = 'creator_exited'

A box or stream is published under the name, and the process that created it has exited.