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
¶
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 raisesLockTimeoutError; 5.0 by default, finite and in(0, 86400].identity: a non-empty string without|, by default the class'smodule.qualname, with__mp_main__read as__main__. It enters the schema hash, and names the box whennameis 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 whosewatchoreventsis in use holds one slot, counted across every process. A watcher that finds every slot taken logs a warning to thesharedboxlogger 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 withmetadatagets 65536, and any other box no area, soupdatewithmetadataon it raisesMetadataFullError.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 |
ValueError
|
When the class is defined, for a |
OverflowError
|
When the class is defined or called, or a field is assigned, with
an |
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.
metadata
property
¶
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
¶
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
¶
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
class-attribute
instance-attribute
¶
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 |
SegmentNotFoundError
|
On Linux, if no segment has that name. |
create
classmethod
¶
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 |
attach
classmethod
¶
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 |
metadata_at
¶
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
¶
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 |
ValueError
|
If a |
MetadataFullError
|
With |
LockTimeoutError
|
If another writer holds the lock longer than the lock timeout. |
BoxClosedError
|
If the box is closed. |
snapshot
¶
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 |
False
|
Raises:
| Type | Description |
|---|---|
BrokenReferenceError
|
With |
UnknownBoxClassError
|
With |
read_into
¶
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
|
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the field is not an array field, or |
ValueError
|
If the box has no such field, or |
LockTimeoutError
|
If another writer holds the lock longer than the lock timeout. |
BoxClosedError
|
If the box is closed. |
writing
¶
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 |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the field is not an array field, or |
ValueError
|
If the box has no such field, or |
LockTimeoutError
|
If another writer holds the lock longer than the lock timeout. |
BoxClosedError
|
If the box is closed. |
locked
¶
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 |
LockTimeoutError
|
If another writer holds the lock longer than the lock timeout. |
BoxClosedError
|
If the box is closed. |
watch
¶
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 |
TypeError
|
If |
force_unlock
¶
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__
¶
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 |
None
|
Raises:
| Type | Description |
|---|---|
BufferError
|
If the major version of |
NotImplementedError
|
If any other keyword is given. |
Notes
On Windows the segment stays in existence while a handle is held.
close
¶
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 |
True
|
repr
|
bool
|
False leaves the field out of |
True
|
kw_only
|
bool | Any
|
Make this field keyword-only or not, whatever the |
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 |
TypeError
|
When the class is defined, for |
fields
¶
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.
default_factory
instance-attribute
¶
A function of no arguments, or dataclasses.MISSING.
kw_only
instance-attribute
¶
True if the constructor takes the value by keyword only; dataclasses.MISSING until the class is created.
metadata
instance-attribute
¶
Read-only; kept in Python, never stored in the segment.
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.
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
¶
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
¶
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
¶
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
¶
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, |
ValueError
|
If a part does not fit its type. |
OverflowError
|
If |
BoxClosedError
|
If the box is closed. |
__call__
¶
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 |
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
¶
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 |
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
¶
publish
¶
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, |
ValueError
|
If a part does not fit its type. |
OverflowError
|
If |
BoxClosedError
|
If the box is closed. |
set
¶
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 |
ValueError
|
If |
BoxClosedError
|
If the box is closed. |
serve
¶
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 |
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 |
None
|
doc
|
Mapping[Any, Any] | None
|
As |
None
|
AttrValue
¶
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.
result
¶
Block until the answer arrives and return the handler's result.
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If no answer arrived within |
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 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 |
LockTimeoutError
|
If the box's write lock stayed held. Call |
BoundedList
¶
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. |
insert
¶
Insert an element before index, clamped to the value as list.insert clamps it.
Raises:
| Type | Description |
|---|---|
OverflowError
|
If |
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
¶
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
¶
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
¶
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 |
IndexError
|
If the value is empty or has no such element. |
remove
¶
Remove the first element equal to value.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no element is equal to |
index
¶
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 |
copy
¶
Return a new value of the same element type and capacity holding the same elements.
The slots are copied without decoding an element.
BoundedSet
¶
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. |
add
¶
Add value unless the set holds it.
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
remove
¶
pop
¶
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. |
update
¶
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 |
isdisjoint
¶
Return whether this set holds none of the elements of other.
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
copy
¶
Return a new value of the same element type and capacity holding the same elements.
The slots are copied without decoding an element.
BoundedDict
¶
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
dataclass
¶
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 |
ValueError
|
If |
size
instance-attribute
¶
Bytes for text and bytes, not characters: a UTF-8 character can take up to 4 bytes; elements for a collection.
segment_status
¶
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 |
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
¶
No box or stream is published under the name.
RUNNING
class-attribute
instance-attribute
¶
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
¶
A box or stream is published under the name, and the process that created it has exited.