dataclass

class trame.app.dataclass.ClientOnly(_type, default=None, convert: FieldEncoder = None, has_dataclass: bool = False, client_deep_reactive: bool = False, type_checking: TypeValidation = TypeValidation.WARNING)

Bases: ServerOnly

Descriptor for a field that is synchronized from server to client only.

The server can read and write the field, and changes are pushed to the client. Client-side edits are intentionally not propagated back to the server.

Use this when client-side reactivity is needed but the server does not need to be kept in sync — e.g. fast-paced updates like mouse location tracking for local tooltip positioning.

Inherits all constructor parameters from ServerOnly.

class trame.app.dataclass.FieldEncoder(encoder, decoder)

Bases: object

Pair of encoder/decoder callables for a field that requires custom serialization.

The encoder converts the Python value to a JSON-serializable form for client transport; the decoder reconstructs the Python value from the received JSON data.

class trame.app.dataclass.ServerOnly(_type, default=None, convert: FieldEncoder = None, has_dataclass: bool = False, client_deep_reactive: bool = False, type_checking: TypeValidation = TypeValidation.WARNING)

Bases: object

Descriptor for a field that exists only on the server (never sent to the client).

Use this for derived values, configuration, or heavyweight objects that should not be serialized. The field participates in watchers but is excluded from any synchronization.

Args:

_type: the Python type annotation (used for type-checking). default: default value or zero-argument callable returning the default. convert: optional FieldEncoder for custom serialization (rarely needed

for server-only fields).

has_dataclass: True when the value holds a StateDataModel instance

or a container of them; automatically sets up the appropriate encoder/decoder.

client_deep_reactive: reserved for subclass Sync — ignored here. type_checking: how type mismatches are reported (default: WARNING).

class trame.app.dataclass.StateDataModel(trame_server=None, enable_collaboration=False, **kwargs)

Bases: object

Base class for reactive data models that synchronize state between server and client.

Declare fields as class-level descriptors (Sync, ServerOnly, ClientOnly) to define which data is shared and in which direction. When a field value changes the model automatically schedules a flush to push the delta to all connected clients.

Example:

class MyModel(StateDataModel):
    count: int = Sync(int, default=0)
    label: str = Sync(str, default="")

model = MyModel(trame_server=server)
model.count = 42  # triggers async push to client
classmethod generate_gui(trame_server=None) str

Return the Vue template string for this model’s auto-generated GUI.

Override in a subclass to produce a dynamic template (e.g. one that depends on server-side configuration). The default implementation returns the class-level TEMPLATE attribute, or an empty string.

register_flush_implementation(push_function)

Set the low-level callable used to push state deltas to the client.

Called automatically by the protocol layer; should not be needed in application code.

update(**kwargs)

Set multiple fields at once; silently ignores keys that are not declared fields.

clear_watchers()

Remove all registered watcher callbacks from this instance.

new_instance()

Create a new, independent instance of the same model class using the same server.

async completion()

Await until all in-flight async flush/watcher tasks have finished.

watch(field_names: Sequence[str], callback_func: Callable[[Any], None | Awaitable[None]], sync: bool = False, eager: bool = False) Callable

Register a callback to be called when one or more fields change.

Args:

field_names (list[str]): Name(s) of the field(s) to watch. callback_func (callable): Callback function to be called when the field(s) change. sync (bool): Whether to execute the callback synchronously. By default this get triggered asynchronously. eager (bool): Whether to execute the callback immediately after registration.

Returns:

callable: Unwatch function to unregister the callback.

provide_as(name, always=False) Provider

Register a data provider to be used by the client.

Args:

name (str): Name of the data variable that will be available within the nested scope. always (bool): Set it to true if you want the template to always be displayed even if the data is not fully loaded.

Returns:

widget: instance of the widget to put within your UI definition.

property server

The trame server this model is registered with, or None if unbound.

property client_state

Return the full JSON-serializable state dict sent to the client.

Applies any registered encoders and ensures all CLIENT_NAMES fields are populated, including ones that were dirtied since the last flush.

update_from_client_state(partial_state)

Apply a partial state dict received from the client back to server-side fields.

Decodes values using registered decoders before assignment. When collaboration mode is disabled the raw client values are also cached in _client_state to avoid a spurious round-trip on the next flush.

dirty(*keys)

Mark one or more fields as dirty and immediately trigger watchers and a flush.

Useful when a mutable field (e.g. a list or dict) is mutated in-place and the descriptor’s __set__ is never called, so the change would otherwise go unnoticed.

flush(dirty_set: set[str] | None = None, force_push=False)

Push pending state changes to the client over the network.

Args:
dirty_set: explicit set of field names to flush; defaults to the current

internal dirty set and clears it afterwards.

force_push: when True, re-sends all fields in dirty_set even if their

encoded value has not changed since the last flush.

class trame.app.dataclass.Sync(_type, default=None, convert: FieldEncoder = None, has_dataclass: bool = False, client_deep_reactive: bool = False, type_checking: TypeValidation = TypeValidation.WARNING)

Bases: ServerOnly

Descriptor for a field that is synchronized between server and client in both directions.

Set client_deep_reactive=True when the value is a nested object that the client template needs to observe at a property level (e.g. a reactive list of objects).

class trame.app.dataclass.TypeValidation(*values)

Bases: Enum

Controls how type mismatches are handled when a field value is set.

  • STRICT: raises TypeError immediately on mismatch.

  • WARNING: logs a warning but allows the assignment.

  • SKIP: performs no type checking.

trame.app.dataclass.copy(src, dst, *keys)

Copy the values of the given field names from src to dst.

trame.app.dataclass.get_instance(instance_id: str)

Return the live StateDataModel instance for the given ID, or None if collected.

IDs are short-lived: once the Python object is garbage-collected the ID becomes invalid. This function is primarily used by decoders that receive an ID from the client.

trame.app.dataclass.watch(*args, **kwargs)

Method decorator that registers the decorated method as a field watcher.

Pass the field name(s) to observe as positional arguments. Additional keyword arguments (sync, eager) are forwarded to watch().

Example:

class MyModel(StateDataModel):
    count = Sync(int, default=0)

    @watch("count")
    def on_count_change(self, count):
        print(f"count changed to {count}")