Skip to content

Syncwave

Syncwave

Syncwave(root_path: str | Path = 'syncstores')

Bases: MutableMapping[str, Any], Reactive

The main entry point to Syncwave.

Start by creating an instance to interact with the stores.

Example:

from syncwave import Syncwave

syncwave = Syncwave()


Usage Documentation

Syncwave

Parameters:

Name Type Description Default
root_path str | Path

Directory holding the stores' JSON files. Created if it doesn't exist.

'syncstores'
Source code in src/syncwave/syncwave.py
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, root_path: str | Path = "syncstores") -> None:
    """Create a `Syncwave` instance.

    Args:
        root_path: Directory holding the stores' JSON files. Created if it doesn't
            exist.

    """
    root = io.sanitize_path(root_path)
    io.create_dir(root)
    self.__root_path = root
    self.__stores: dict[str, tuple[Any, StoreInfo]] = {}

root_path property

root_path: Path

The absolute path to the directory holding the stores' JSON files.


Usage Documentation

The syncwave Instance

create_store

create_store(
    tp: TypeForm[T], /, *, name: str, default: Any = void
) -> T

Create a store, persisted to <root_path>/<name>.json and two-way synced.

Every change to the store, from Python or from the file, is validated against tp.

Example:

from syncwave import SyncSet, Syncwave

syncwave = Syncwave()

tags = syncwave.create_store(SyncSet[str], name="tags")
tags.add("python")


Usage Documentation

Create a Store

Parameters:

Name Type Description Default
tp TypeForm[T]

Type of the store, e.g. list[int], SyncSet[str], or a SyncModel.

required
name str

Name of the store, used as its key and as its file name.

required
default Any

Initial value, used if the file is missing or empty. Required when no empty value ({}, [], "", or None) fits tp.

void

Returns:

Type Description
T

The store's value: the live object for a reactive type, a copy otherwise.

Source code in src/syncwave/syncwave.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def create_store(self, tp: TypeForm[T], /, *, name: str, default: Any = void) -> T:
    """Create a store, persisted to `<root_path>/<name>.json` and two-way synced.

    Every change to the store, from Python or from the file, is validated against
    `tp`.

    Example:
    ```python
    from syncwave import SyncSet, Syncwave

    syncwave = Syncwave()

    tags = syncwave.create_store(SyncSet[str], name="tags")
    tags.add("python")
    ```

    ---

    Abstract: Usage Documentation
        [Create a Store](https://syncwave.dev/usage/syncwave/#create-a-store)

    Args:
        tp: Type of the store, e.g. `list[int]`, `SyncSet[str]`, or a `SyncModel`.
        name: Name of the store, used as its key and as its file name.
        default: Initial value, used if the file is missing or empty. Required when
            no empty value (`{}`, `[]`, `""`, or `None`) fits `tp`.

    Returns:
        The store's value: the live object for a reactive type, a copy otherwise.

    """
    if name in self.__stores:
        raise ValueError(f"Store '{name}' already exists.")
    str_guard("name", name)
    io.file_name_guard(name)

    self.__create_store(tp, name, default)
    value, store_info = self.__stores[name]
    return detach(value, store_info.type_adapter)

store

store(
    *,
    name: str,
    collection: type[SyncDict[Any, Never] | SyncList[Never]]
    | Literal["auto"]
    | None = "auto",
    default: Any = void,
) -> Callable[
    [type[SyncModelLike_T]], type[SyncModelLike_T]
]

Class decorator creating a store from a reactive model.

Like create_store, but the model is wrapped in a collection first (see collection). The class is returned unchanged.

Example:

from syncwave import SyncModel, Syncwave

syncwave = Syncwave()


@syncwave.store(name="customers")
class Customer(SyncModel):
    name: str
    age: int


customers = syncwave["customers"]  # a SyncList[Customer]
customers.append(Customer(name="Alice", age=30))


Usage Documentation

The store Decorator

Parameters:

Name Type Description Default
name str

Name of the store, used as its key and as its file name.

required
collection type[SyncDict[Any, Never] | SyncList[Never]] | Literal['auto'] | None

SyncList, SyncDict (str keys) or SyncDict[<key type>], or None for no wrapping. "auto" picks None for a SyncRoot, a SyncDict if the model has a key field, and SyncList otherwise.

'auto'
default Any

Initial value, used if the file is missing or empty. Pass plain data (e.g. a dict or a list), not an instance.

void

Returns:

Type Description
Callable[[type[SyncModelLike_T]], type[SyncModelLike_T]]

A decorator that creates the store and returns the class unchanged.

Source code in src/syncwave/syncwave.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def store(
    self,
    *,
    name: str,
    collection: type[SyncDict[Any, Never] | SyncList[Never]]
    | Literal["auto"]
    | None = "auto",
    default: Any = void,
) -> F[[type[SyncModelLike_T]], type[SyncModelLike_T]]:
    """Class decorator creating a store from a reactive model.

    Like `create_store`, but the model is wrapped in a collection first (see
    `collection`). The class is returned unchanged.

    Example:
    ```python
    from syncwave import SyncModel, Syncwave

    syncwave = Syncwave()


    @syncwave.store(name="customers")
    class Customer(SyncModel):
        name: str
        age: int


    customers = syncwave["customers"]  # a SyncList[Customer]
    customers.append(Customer(name="Alice", age=30))
    ```

    ---

    Abstract: Usage Documentation
        [The `store` Decorator](https://syncwave.dev/usage/models/#the-store-decorator)

    Args:
        name: Name of the store, used as its key and as its file name.
        collection: `SyncList`, `SyncDict` (`str` keys) or `SyncDict[<key type>]`,
            or `None` for no wrapping. `"auto"` picks `None` for a `SyncRoot`, a
            `SyncDict` if the model has a `key` field, and `SyncList` otherwise.
        default: Initial value, used if the file is missing or empty. Pass plain
            data (e.g. a `dict` or a `list`), not an instance.

    Returns:
        A decorator that creates the store and returns the class unchanged.

    """
    if name in self.__stores:
        raise ValueError(f"Store '{name}' already exists.")
    str_guard("name", name)
    io.file_name_guard(name)

    def decorator(cls: type[SyncModelLike_T]) -> type[SyncModelLike_T]:
        if not isclass(cls):
            raise TypeError(f"Expected a class, got `{type(cls).__qualname__}`.")

        if issubclass(cls, SyncModel) or is_sync_dataclass(cls):
            store_tp = collection_wrap(cls, collection)
            self.__create_store(store_tp, name, default)
            return cls

        err = "Use %s instead of a %s."
        if issubclass(cls, BaseModel):
            raise TypeError(err % ("a `SyncModel`", "`BaseModel`"))
        if is_pydantic_dataclass(cls):
            raise TypeError(err % ("`@sync_dataclass`", "Pydantic dataclass"))
        if is_dataclass(cls):
            undecorated_guard(cls)
            raise TypeError(err % ("`@sync_dataclass`", "standard dataclass"))
        raise TypeError(
            "Expected a `SyncModel` or a reactive dataclass, "
            f"but got `{cls.__qualname__}` instead."
        )

    return decorator