ws_sync.decorators

Simple function decorators to mark attributes and methods for syncing with the frontend.

There are two types of decorators:

  1. Decorate __init__(): For declaring attributes to be synced with the frontend:
    • @sync(): sync the specified attributes
    • @sync_all(): sync all (non-private) attributes by default
    • @sync_only(): sync only the attributes specified as keyword arguments
  2. Decorate a method: For declaring methods to be exposed to the frontend:
    • @remote_action("MY_ACTION"): expose a method as an action (blocks the backend logic, non-concurrent, non-cancellable)
    • @remote_task("MY_TASK"): expose a method as a long-running task (non-blocking, concurrent, cancellable)
    • @remote_task_cancel("MY_TASK"): expose a method as a task-canceller (cancels a running task)

After decorating the __init__() method, the object will have a sync attribute that can be called to sync the object's state with the frontend, e.g. await self.sync(). As you can see, the sync attribute is a coroutine, so you should await it.

Note that private attribute means an attribute that starts with an underscore.

Example:

class Notepad:
    @sync_all("NOTEPAD")
    def __init__(self):
        self.text = ""  # will be synced
        self._private = "private"  # won't be synced, due to underscore prefix

    @property  # will be synced just like a normal attribute
    def length(self):
        return len(self.text)

    @remote_action("CLEAR")
    async def clear(self):
        self.text = ""
        await self.sync()  # sync the state to update the frontend

    @remote_task("GROW")
    async def grow(self):
        self.growing = True  # since this was not declared in __init__, it isn't registered for syncing
        while self.growing:
            self.text += "a"
            await self.sync()  # sync the state to update the frontend
            await asyncio.sleep(1)

    @grow.cancel  # syntactic sugar for remote_task_cancel("GROW")
    async def stop_grow(self):
        self.growing = False

More advanced example:

class Calendar:
    @sync_only(
        "CAL",
        current_day=...,
        length="size",
        _toCamelCase=True,
        _expose_running_tasks=True,
    )
    def __init__(self):
        self.current_day = (
            "monday"  # will be synced as "currentDay", since _toCamelCase=True
        )
        self.length = 0  # will be synced as "size"
        self.private = None  # won't be synced, since not specified

    @remote_action("NEXT_DAY")
    async def next_day(self):
        self.current_day = "tuesday"
        await self.sync()  # sync the state to update the frontend

    @remote_task("FAST_FORWARD")
    async def fast_forward(self):
        for i in range(100):
            self.length += 1
            await self.sync(
                if_since_last=0.1
            )  # sync, but only if 0.1 seconds have passed since the last sync
        await self.sync.toast(
            "Fast forward complete!", type="success"
        )  # send a toast to the frontend

    @remote_action("IMPORT_EVENTS")
    async def import_events(self, data: bytes):  # from `sendBinary` in the frontend
        pickle.loads(data)  # do something with the data
   
  1"""
  2Simple function decorators to mark attributes and methods for syncing with the frontend.
  3
  4There are two types of decorators:
  51. **Decorate `__init__()`**: For declaring attributes to be synced with the frontend:
  6    - `@sync()`: sync the specified attributes
  7    - `@sync_all()`: sync all (non-private) attributes by default
  8    - `@sync_only()`: sync only the attributes specified as keyword arguments
  92. **Decorate a method**: For declaring methods to be exposed to the frontend:
 10    - `@remote_action("MY_ACTION")`: expose a method as an action (blocks the backend logic, non-concurrent, non-cancellable)
 11    - `@remote_task("MY_TASK")`: expose a method as a long-running task (non-blocking, concurrent, cancellable)
 12    - `@remote_task_cancel("MY_TASK")`: expose a method as a task-canceller (cancels a running task)
 13
 14After decorating the `__init__()` method, the object will have a `sync` attribute that can be called to sync the object's state with the frontend, e.g. `await self.sync()`.
 15As you can see, the `sync` attribute is a coroutine, so you should `await` it.
 16
 17*Note that private attribute means an attribute that starts with an underscore.*
 18
 19Example:
 20```python
 21class Notepad:
 22    @sync_all("NOTEPAD")
 23    def __init__(self):
 24        self.text = ""  # will be synced
 25        self._private = "private"  # won't be synced, due to underscore prefix
 26
 27    @property  # will be synced just like a normal attribute
 28    def length(self):
 29        return len(self.text)
 30
 31    @remote_action("CLEAR")
 32    async def clear(self):
 33        self.text = ""
 34        await self.sync()  # sync the state to update the frontend
 35
 36    @remote_task("GROW")
 37    async def grow(self):
 38        self.growing = True  # since this was not declared in __init__, it isn't registered for syncing
 39        while self.growing:
 40            self.text += "a"
 41            await self.sync()  # sync the state to update the frontend
 42            await asyncio.sleep(1)
 43
 44    @grow.cancel  # syntactic sugar for remote_task_cancel("GROW")
 45    async def stop_grow(self):
 46        self.growing = False
 47
 48```
 49
 50More advanced example:
 51```python
 52class Calendar:
 53    @sync_only(
 54        "CAL",
 55        current_day=...,
 56        length="size",
 57        _toCamelCase=True,
 58        _expose_running_tasks=True,
 59    )
 60    def __init__(self):
 61        self.current_day = (
 62            "monday"  # will be synced as "currentDay", since _toCamelCase=True
 63        )
 64        self.length = 0  # will be synced as "size"
 65        self.private = None  # won't be synced, since not specified
 66
 67    @remote_action("NEXT_DAY")
 68    async def next_day(self):
 69        self.current_day = "tuesday"
 70        await self.sync()  # sync the state to update the frontend
 71
 72    @remote_task("FAST_FORWARD")
 73    async def fast_forward(self):
 74        for i in range(100):
 75            self.length += 1
 76            await self.sync(
 77                if_since_last=0.1
 78            )  # sync, but only if 0.1 seconds have passed since the last sync
 79        await self.sync.toast(
 80            "Fast forward complete!", type="success"
 81        )  # send a toast to the frontend
 82
 83    @remote_action("IMPORT_EVENTS")
 84    async def import_events(self, data: bytes):  # from `sendBinary` in the frontend
 85        pickle.loads(data)  # do something with the data
 86    ```
 87"""
 88
 89from collections.abc import Callable
 90from logging import Logger
 91from types import EllipsisType
 92from typing import cast, overload
 93
 94
 95@overload  # Usage without parentheses
 96def sync[F: Callable](func: F, /) -> F: ...
 97
 98
 99@overload  # Usage with parentheses
100def sync[F: Callable](
101    *,
102    key: str | None = None,
103    sync_all: bool = False,
104    include: dict[str, str | EllipsisType] | list[str] | None = None,
105    exclude: list[str] | None = None,
106    toCamelCase: bool | None = None,  # noqa: N803
107    send_on_init: bool = True,
108    expose_running_tasks: bool = False,
109    logger: Logger | None = None,
110) -> Callable[[F], F]: ...
111
112
113def sync[F: Callable](
114    func: F | None = None,
115    /,
116    *,
117    key: str | None = None,
118    sync_all: bool = False,
119    include: dict[str, str | EllipsisType] | list[str] | None = None,
120    exclude: list[str] | None = None,
121    toCamelCase: bool | None = None,  # noqa: N803
122    send_on_init: bool = True,
123    expose_running_tasks: bool = False,
124    logger: Logger | None = None,
125) -> F | Callable[[F], F]:
126    """
127    Decorator for `__init__()` or Class: Register the attributes that should be synced with the frontend.
128
129    Args:
130        func: implicitly passed when used as a decorator
131        key: unique key (matching the frontend key) to identify the object.
132             If None, defaults to the class name.
133        sync_all: sync all non-private attributes
134        include: attribute names to sync, value being either ... or a string of the key of the attribute
135        exclude: list of attributes to exclude from syncing
136        toCamelCase: convert attribute names to camelCase
137        send_on_init: send the state on connection init
138        expose_running_tasks: expose the list in the synced state as `running_tasks` or `runningTasks`
139        logger: logger to use for logging
140    """
141    from pydantic import BaseModel  # noqa: PLC0415
142
143    from .sync import Sync  # noqa: PLC0415
144    from .synced_model import Synced  # noqa: PLC0415
145
146    def _process_class(cls: type) -> type:
147        # For Pydantic models, require Synced mixin
148        if issubclass(cls, BaseModel) and not issubclass(cls, Synced):
149            msg = (
150                f"Pydantic model {cls.__name__} with @sync_all() or @sync_only() decorator "
151                "must inherit from ws_sync.Synced mixin.\n"
152                f"Change: class {cls.__name__}(BaseModel) -> class {cls.__name__}(Synced, BaseModel)"
153            )
154            raise TypeError(msg)
155
156        # Store configuration on the class
157        cls._sync_config = {  # type: ignore
158            "key": key,
159            "sync_all": sync_all,
160            "include": include,
161            "exclude": exclude,
162            "toCamelCase": toCamelCase,
163            "send_on_init": send_on_init,
164            "expose_running_tasks": expose_running_tasks,
165            "logger": logger,
166        }
167
168        def _initialize_sync(self):  # noqa: ANN001
169            """Initialize Sync object. Called from __init__ wrapper or model_post_init."""
170            # Check if the subclass has a different sync configuration
171            if (
172                type(self) is not cls
173                and getattr(type(self), "_sync_config", None) is not cls._sync_config  # type: ignore
174            ):
175                # The subclass has overridden the sync configuration,
176                # so we shouldn't instantiate Sync here.
177                return
178
179            # Instantiate Sync
180            sync_key = key if isinstance(key, str) else type(self).__name__
181
182            sync_obj = Sync(
183                obj=self,
184                key=sync_key,
185                sync_all=sync_all,
186                include=include,
187                exclude=exclude or [],
188                toCamelCase=toCamelCase,
189                send_on_init=send_on_init,
190                expose_running_tasks=expose_running_tasks,
191                logger=logger,
192            )
193
194            # Set sync object (Synced mixin has the property and _sync private attr)
195            self.sync = sync_obj
196
197        # For Pydantic models, override model_post_init to call user's version then init Sync
198        # This ensures Sync is initialized AFTER all user model_post_init logic runs
199        # This works for ALL construction paths: __init__(), model_validate(), model_construct(), etc.
200        if issubclass(cls, BaseModel):
201            # Get user's model_post_init if they defined one
202            user_model_post_init = cls.__dict__.get("model_post_init")
203
204            # Get Synced's model_post_init (the base implementation)
205            synced_model_post_init = Synced.model_post_init  # type: ignore
206
207            def wrapped_model_post_init(self, __context, /):  # noqa: ANN001
208                # First, call user's model_post_init if they defined one
209                if user_model_post_init is not None:
210                    user_model_post_init(self, __context)
211                else:
212                    # Call Synced's default (empty) model_post_init
213                    synced_model_post_init(self, __context)
214
215                # Finally, initialize Sync AFTER all user initialization is complete
216                _initialize_sync(self)
217
218            cls.model_post_init = wrapped_model_post_init  # type: ignore
219        else:
220            # For regular classes, wrap __init__
221            original_init = cls.__init__
222
223            def init_wrapper(self, *args, **kwargs):  # noqa: ANN001
224                original_init(self, *args, **kwargs)
225                _initialize_sync(self)
226
227            cls.__init__ = init_wrapper
228
229        return cls
230
231    def _process_init(init_func: F) -> F:
232        def wrapper(self, *args, **kwargs):  # noqa: ANN001
233            init_func(self, *args, **kwargs)
234
235            sync_key = key if isinstance(key, str) else type(self).__name__
236
237            self.sync = Sync(
238                obj=self,
239                key=sync_key,
240                sync_all=sync_all,
241                include=include,
242                exclude=exclude or [],
243                toCamelCase=toCamelCase,
244                send_on_init=send_on_init,
245                expose_running_tasks=expose_running_tasks,
246                logger=logger,
247            )
248
249        return wrapper  # type: ignore
250
251    def decorator(target: F) -> F:
252        if isinstance(target, type):
253            return cast(F, _process_class(target))
254        return _process_init(target)
255
256    if func is None:  # @sync without parentheses
257        return decorator
258    # @sync(...) was used
259    return decorator(func)
260
261
262def sync_all(
263    key: str | None = None,
264    *,
265    include: dict[str, str | EllipsisType] | list[str] | None = None,
266    exclude: list[str] | None = None,
267    toCamelCase: bool | None = None,  # noqa: N803
268    send_on_init: bool = True,
269    expose_running_tasks: bool = False,
270    logger: Logger | None = None,
271):
272    """
273    Decorator for `__init__()`: Register all non-private attributes to be synced with the frontend.
274
275    Args:
276        key: unique key (matching the frontend key) to identify the object.
277             If None, defaults to the class name.
278        include: attribute names to sync, value being either ... or a string of the key of the attribute
279        exclude: list of attributes to exclude from syncing
280        toCamelCase: convert attribute names to camelCase
281        send_on_init: send the state on connection init
282        expose_running_tasks: expose the list in the synced state as `running_tasks` or `runningTasks`
283        logger: logger to use for logging
284    """
285    return sync(
286        key=key,
287        sync_all=True,
288        include=include,
289        exclude=exclude or [],
290        toCamelCase=toCamelCase,
291        send_on_init=send_on_init,
292        expose_running_tasks=expose_running_tasks,
293        logger=logger,
294    )
295
296
297def sync_only(
298    _key: str | None = None,
299    *,
300    _toCamelCase: bool | None = None,  # noqa: N803
301    _send_on_init: bool = True,
302    _expose_running_tasks: bool = False,
303    _logger: Logger | None = None,
304    **sync_attributes: str | EllipsisType,
305):
306    """
307    Decorator for `__init__()`: Register only the keyword-specified attributes to be synced with the frontend.
308
309    Args:
310        _key: unique key (matching the frontend key) to identify the object.
311              If None, defaults to the class name.
312        _toCamelCase: convert attribute names to camelCase
313        _send_on_init: send the state on connection init
314        _expose_running_tasks: expose the list in the synced state as `running_tasks` or `runningTasks`
315        _logger: logger to use for logging
316        **sync_attributes: attribute names to sync, value being the key of the attribute
317    """
318    return sync(
319        key=_key,
320        sync_all=False,
321        include=sync_attributes,
322        exclude=[],
323        toCamelCase=_toCamelCase,
324        send_on_init=_send_on_init,
325        expose_running_tasks=_expose_running_tasks,
326        logger=_logger,
327    )
328
329
330@overload  # Usage without parentheses
331def remote_action[F: Callable](key: F) -> F: ...
332
333
334@overload  # Usage with parentheses
335def remote_action[F: Callable](key: str | None = None) -> Callable[[F], F]: ...
336
337
338def remote_action[F: Callable](key: str | None | F = None) -> F | Callable[[F], F]:
339    """
340    Decorator for methods: Expose the method as an action to the frontend.
341
342    An action is a "synchronous" method that blocks the backend logic until it completes.
343    Of course, the method should be `async` to allow for non-blocking concurrency with other parallel sessions of the server.
344
345    Args:
346        key: unique key (matching the frontend key) to identify the action.
347             If None, defaults to the method name.
348    """
349
350    def decorator(func: F) -> F:
351        action_key = key if isinstance(key, str) else func.__name__
352        func.remote_action = action_key  # type: ignore
353        return func
354
355    if callable(key):  # @remote_action without parentheses
356        func = key  # key is actually the function
357        return decorator(func)
358    # @remote_action(...) was used
359    decorator.forgot_to_call = True  # type: ignore[reportFunctionMemberAccess]
360    return decorator
361
362
363def find_remote_actions(cls: type) -> dict[str, Callable]:
364    """
365    Find all remote actions in a class.
366
367    Returns a dictionary of action keys to the function.
368    """
369    actions: dict[str, Callable] = {}
370    for base in reversed(cls.__mro__):
371        if base is object:
372            continue
373        for attr in base.__dict__.values():
374            if isinstance(attr, property):
375                continue
376            if callable(attr) and hasattr(attr, "remote_action"):
377                actions[attr.remote_action] = attr  # type: ignore[reportFunctionMemberAccess]
378    return actions
379
380
381@overload  # Usage without parentheses
382def remote_task[F: Callable](key: F) -> F: ...
383
384
385@overload  # Usage with parentheses
386def remote_task[F: Callable](key: str | None = None) -> Callable[[F], F]: ...
387
388
389def remote_task[F: Callable](key: str | None | F = None) -> F | Callable[[F], F]:
390    """
391    Decorator for methods: Expose the method as a long-running task to the frontend.
392
393    A task is a "non-blocking" method that runs concurrently with the backend logic.
394    The frontend can cancel the task at any time, so you should also implement a `@remote_task_cancel` method to cancel the task.
395
396    Args:
397        key: unique key (matching the frontend key) to identify the task.
398             If None, defaults to the method name.
399    """
400
401    def decorator(func: F) -> F:
402        task_key = key if isinstance(key, str) else func.__name__
403        func.remote_task = task_key  # type: ignore
404        func.cancel = remote_task_cancel(task_key)  # type: ignore # syntactic sugar
405        return func
406
407    if callable(key):  # @remote_task without parentheses
408        func = key  # key is actually the function
409        return decorator(func)
410    # @remote_task(...) was used
411    decorator.forgot_to_call = True  # type: ignore[reportFunctionMemberAccess]
412    return decorator
413
414
415def find_remote_tasks(cls: type) -> dict[str, Callable]:
416    """
417    Find all remote tasks in a class.
418
419    Returns a dictionary of task keys to the function.
420    """
421    tasks: dict[str, Callable] = {}
422    for attr_name in dir(cls):
423        try:
424            attr = getattr(cls, attr_name)
425        except AttributeError:
426            continue
427        if isinstance(attr, property):
428            continue
429        if callable(attr) and hasattr(attr, "remote_task"):
430            tasks[attr.remote_task] = attr  # type: ignore[reportFunctionMemberAccess]
431    return tasks
432
433
434def remote_task_cancel[F: Callable](key: str) -> Callable[[F], F]:
435    """
436    Decorator for methods: Expose the method as a task-canceller to the frontend.
437
438    A task-canceller is a method that cancels a running task.
439    The method `f` decorated with `@remote_task` has a corresponding cancel decorator `@f.cancel`:
440    ```python
441    @remote_task("MY_TASK")
442    async def my_task(self): ...
443
444    @my_task.cancel
445    async def cancel_my_task(self): ...
446    ```
447
448    Args:
449        key: unique key (matching the frontend key) to identify the task
450    """
451
452    def decorator(func: F) -> F:
453        func.remote_task_cancel = key  # type: ignore
454        return func
455
456    decorator.forgot_to_call = True  # type: ignore[reportFunctionMemberAccess]
457    return decorator
458
459
460def find_remote_task_cancellers(cls: type) -> dict[str, Callable]:
461    """
462    Find all remote task-cancellers in a class.
463
464    Returns a dictionary of task-canceller keys to the function.
465    """
466    cancellers: dict[str, Callable] = {}
467    for attr_name in dir(cls):
468        try:
469            attr = getattr(cls, attr_name)
470        except AttributeError:
471            continue
472        if isinstance(attr, property):
473            continue
474        if callable(attr) and hasattr(attr, "remote_task_cancel"):
475            cancellers[attr.remote_task_cancel] = attr  # type: ignore[reportFunctionMemberAccess]
476    return cancellers
def sync( func: Optional[F] = None, /, *, key: str | None = None, sync_all: bool = False, include: dict[str, str | ellipsis] | list[str] | None = None, exclude: list[str] | None = None, toCamelCase: bool | None = None, send_on_init: bool = True, expose_running_tasks: bool = False, logger: logging.Logger | None = None) -> Union[F, Callable[[F], F]]:
114def sync[F: Callable](
115    func: F | None = None,
116    /,
117    *,
118    key: str | None = None,
119    sync_all: bool = False,
120    include: dict[str, str | EllipsisType] | list[str] | None = None,
121    exclude: list[str] | None = None,
122    toCamelCase: bool | None = None,  # noqa: N803
123    send_on_init: bool = True,
124    expose_running_tasks: bool = False,
125    logger: Logger | None = None,
126) -> F | Callable[[F], F]:
127    """
128    Decorator for `__init__()` or Class: Register the attributes that should be synced with the frontend.
129
130    Args:
131        func: implicitly passed when used as a decorator
132        key: unique key (matching the frontend key) to identify the object.
133             If None, defaults to the class name.
134        sync_all: sync all non-private attributes
135        include: attribute names to sync, value being either ... or a string of the key of the attribute
136        exclude: list of attributes to exclude from syncing
137        toCamelCase: convert attribute names to camelCase
138        send_on_init: send the state on connection init
139        expose_running_tasks: expose the list in the synced state as `running_tasks` or `runningTasks`
140        logger: logger to use for logging
141    """
142    from pydantic import BaseModel  # noqa: PLC0415
143
144    from .sync import Sync  # noqa: PLC0415
145    from .synced_model import Synced  # noqa: PLC0415
146
147    def _process_class(cls: type) -> type:
148        # For Pydantic models, require Synced mixin
149        if issubclass(cls, BaseModel) and not issubclass(cls, Synced):
150            msg = (
151                f"Pydantic model {cls.__name__} with @sync_all() or @sync_only() decorator "
152                "must inherit from ws_sync.Synced mixin.\n"
153                f"Change: class {cls.__name__}(BaseModel) -> class {cls.__name__}(Synced, BaseModel)"
154            )
155            raise TypeError(msg)
156
157        # Store configuration on the class
158        cls._sync_config = {  # type: ignore
159            "key": key,
160            "sync_all": sync_all,
161            "include": include,
162            "exclude": exclude,
163            "toCamelCase": toCamelCase,
164            "send_on_init": send_on_init,
165            "expose_running_tasks": expose_running_tasks,
166            "logger": logger,
167        }
168
169        def _initialize_sync(self):  # noqa: ANN001
170            """Initialize Sync object. Called from __init__ wrapper or model_post_init."""
171            # Check if the subclass has a different sync configuration
172            if (
173                type(self) is not cls
174                and getattr(type(self), "_sync_config", None) is not cls._sync_config  # type: ignore
175            ):
176                # The subclass has overridden the sync configuration,
177                # so we shouldn't instantiate Sync here.
178                return
179
180            # Instantiate Sync
181            sync_key = key if isinstance(key, str) else type(self).__name__
182
183            sync_obj = Sync(
184                obj=self,
185                key=sync_key,
186                sync_all=sync_all,
187                include=include,
188                exclude=exclude or [],
189                toCamelCase=toCamelCase,
190                send_on_init=send_on_init,
191                expose_running_tasks=expose_running_tasks,
192                logger=logger,
193            )
194
195            # Set sync object (Synced mixin has the property and _sync private attr)
196            self.sync = sync_obj
197
198        # For Pydantic models, override model_post_init to call user's version then init Sync
199        # This ensures Sync is initialized AFTER all user model_post_init logic runs
200        # This works for ALL construction paths: __init__(), model_validate(), model_construct(), etc.
201        if issubclass(cls, BaseModel):
202            # Get user's model_post_init if they defined one
203            user_model_post_init = cls.__dict__.get("model_post_init")
204
205            # Get Synced's model_post_init (the base implementation)
206            synced_model_post_init = Synced.model_post_init  # type: ignore
207
208            def wrapped_model_post_init(self, __context, /):  # noqa: ANN001
209                # First, call user's model_post_init if they defined one
210                if user_model_post_init is not None:
211                    user_model_post_init(self, __context)
212                else:
213                    # Call Synced's default (empty) model_post_init
214                    synced_model_post_init(self, __context)
215
216                # Finally, initialize Sync AFTER all user initialization is complete
217                _initialize_sync(self)
218
219            cls.model_post_init = wrapped_model_post_init  # type: ignore
220        else:
221            # For regular classes, wrap __init__
222            original_init = cls.__init__
223
224            def init_wrapper(self, *args, **kwargs):  # noqa: ANN001
225                original_init(self, *args, **kwargs)
226                _initialize_sync(self)
227
228            cls.__init__ = init_wrapper
229
230        return cls
231
232    def _process_init(init_func: F) -> F:
233        def wrapper(self, *args, **kwargs):  # noqa: ANN001
234            init_func(self, *args, **kwargs)
235
236            sync_key = key if isinstance(key, str) else type(self).__name__
237
238            self.sync = Sync(
239                obj=self,
240                key=sync_key,
241                sync_all=sync_all,
242                include=include,
243                exclude=exclude or [],
244                toCamelCase=toCamelCase,
245                send_on_init=send_on_init,
246                expose_running_tasks=expose_running_tasks,
247                logger=logger,
248            )
249
250        return wrapper  # type: ignore
251
252    def decorator(target: F) -> F:
253        if isinstance(target, type):
254            return cast(F, _process_class(target))
255        return _process_init(target)
256
257    if func is None:  # @sync without parentheses
258        return decorator
259    # @sync(...) was used
260    return decorator(func)

Decorator for __init__() or Class: Register the attributes that should be synced with the frontend.

Arguments:
  • func: implicitly passed when used as a decorator
  • key: unique key (matching the frontend key) to identify the object. If None, defaults to the class name.
  • sync_all: sync all non-private attributes
  • include: attribute names to sync, value being either ... or a string of the key of the attribute
  • exclude: list of attributes to exclude from syncing
  • toCamelCase: convert attribute names to camelCase
  • send_on_init: send the state on connection init
  • expose_running_tasks: expose the list in the synced state as running_tasks or runningTasks
  • logger: logger to use for logging
def sync_all( key: str | None = None, *, include: dict[str, str | ellipsis] | list[str] | None = None, exclude: list[str] | None = None, toCamelCase: bool | None = None, send_on_init: bool = True, expose_running_tasks: bool = False, logger: logging.Logger | None = None):
263def sync_all(
264    key: str | None = None,
265    *,
266    include: dict[str, str | EllipsisType] | list[str] | None = None,
267    exclude: list[str] | None = None,
268    toCamelCase: bool | None = None,  # noqa: N803
269    send_on_init: bool = True,
270    expose_running_tasks: bool = False,
271    logger: Logger | None = None,
272):
273    """
274    Decorator for `__init__()`: Register all non-private attributes to be synced with the frontend.
275
276    Args:
277        key: unique key (matching the frontend key) to identify the object.
278             If None, defaults to the class name.
279        include: attribute names to sync, value being either ... or a string of the key of the attribute
280        exclude: list of attributes to exclude from syncing
281        toCamelCase: convert attribute names to camelCase
282        send_on_init: send the state on connection init
283        expose_running_tasks: expose the list in the synced state as `running_tasks` or `runningTasks`
284        logger: logger to use for logging
285    """
286    return sync(
287        key=key,
288        sync_all=True,
289        include=include,
290        exclude=exclude or [],
291        toCamelCase=toCamelCase,
292        send_on_init=send_on_init,
293        expose_running_tasks=expose_running_tasks,
294        logger=logger,
295    )

Decorator for __init__(): Register all non-private attributes to be synced with the frontend.

Arguments:
  • key: unique key (matching the frontend key) to identify the object. If None, defaults to the class name.
  • include: attribute names to sync, value being either ... or a string of the key of the attribute
  • exclude: list of attributes to exclude from syncing
  • toCamelCase: convert attribute names to camelCase
  • send_on_init: send the state on connection init
  • expose_running_tasks: expose the list in the synced state as running_tasks or runningTasks
  • logger: logger to use for logging
def sync_only( _key: str | None = None, *, _toCamelCase: bool | None = None, _send_on_init: bool = True, _expose_running_tasks: bool = False, _logger: logging.Logger | None = None, **sync_attributes: str | ellipsis):
298def sync_only(
299    _key: str | None = None,
300    *,
301    _toCamelCase: bool | None = None,  # noqa: N803
302    _send_on_init: bool = True,
303    _expose_running_tasks: bool = False,
304    _logger: Logger | None = None,
305    **sync_attributes: str | EllipsisType,
306):
307    """
308    Decorator for `__init__()`: Register only the keyword-specified attributes to be synced with the frontend.
309
310    Args:
311        _key: unique key (matching the frontend key) to identify the object.
312              If None, defaults to the class name.
313        _toCamelCase: convert attribute names to camelCase
314        _send_on_init: send the state on connection init
315        _expose_running_tasks: expose the list in the synced state as `running_tasks` or `runningTasks`
316        _logger: logger to use for logging
317        **sync_attributes: attribute names to sync, value being the key of the attribute
318    """
319    return sync(
320        key=_key,
321        sync_all=False,
322        include=sync_attributes,
323        exclude=[],
324        toCamelCase=_toCamelCase,
325        send_on_init=_send_on_init,
326        expose_running_tasks=_expose_running_tasks,
327        logger=_logger,
328    )

Decorator for __init__(): Register only the keyword-specified attributes to be synced with the frontend.

Arguments:
  • _key: unique key (matching the frontend key) to identify the object. If None, defaults to the class name.
  • _toCamelCase: convert attribute names to camelCase
  • _send_on_init: send the state on connection init
  • _expose_running_tasks: expose the list in the synced state as running_tasks or runningTasks
  • _logger: logger to use for logging
  • **sync_attributes: attribute names to sync, value being the key of the attribute
def remote_action(key: Union[str, NoneType, F] = None) -> Union[F, Callable[[F], F]]:
339def remote_action[F: Callable](key: str | None | F = None) -> F | Callable[[F], F]:
340    """
341    Decorator for methods: Expose the method as an action to the frontend.
342
343    An action is a "synchronous" method that blocks the backend logic until it completes.
344    Of course, the method should be `async` to allow for non-blocking concurrency with other parallel sessions of the server.
345
346    Args:
347        key: unique key (matching the frontend key) to identify the action.
348             If None, defaults to the method name.
349    """
350
351    def decorator(func: F) -> F:
352        action_key = key if isinstance(key, str) else func.__name__
353        func.remote_action = action_key  # type: ignore
354        return func
355
356    if callable(key):  # @remote_action without parentheses
357        func = key  # key is actually the function
358        return decorator(func)
359    # @remote_action(...) was used
360    decorator.forgot_to_call = True  # type: ignore[reportFunctionMemberAccess]
361    return decorator

Decorator for methods: Expose the method as an action to the frontend.

An action is a "synchronous" method that blocks the backend logic until it completes. Of course, the method should be async to allow for non-blocking concurrency with other parallel sessions of the server.

Arguments:
  • key: unique key (matching the frontend key) to identify the action. If None, defaults to the method name.
def find_remote_actions(cls: type) -> dict[str, Callable]:
364def find_remote_actions(cls: type) -> dict[str, Callable]:
365    """
366    Find all remote actions in a class.
367
368    Returns a dictionary of action keys to the function.
369    """
370    actions: dict[str, Callable] = {}
371    for base in reversed(cls.__mro__):
372        if base is object:
373            continue
374        for attr in base.__dict__.values():
375            if isinstance(attr, property):
376                continue
377            if callable(attr) and hasattr(attr, "remote_action"):
378                actions[attr.remote_action] = attr  # type: ignore[reportFunctionMemberAccess]
379    return actions

Find all remote actions in a class.

Returns a dictionary of action keys to the function.

def remote_task(key: Union[str, NoneType, F] = None) -> Union[F, Callable[[F], F]]:
390def remote_task[F: Callable](key: str | None | F = None) -> F | Callable[[F], F]:
391    """
392    Decorator for methods: Expose the method as a long-running task to the frontend.
393
394    A task is a "non-blocking" method that runs concurrently with the backend logic.
395    The frontend can cancel the task at any time, so you should also implement a `@remote_task_cancel` method to cancel the task.
396
397    Args:
398        key: unique key (matching the frontend key) to identify the task.
399             If None, defaults to the method name.
400    """
401
402    def decorator(func: F) -> F:
403        task_key = key if isinstance(key, str) else func.__name__
404        func.remote_task = task_key  # type: ignore
405        func.cancel = remote_task_cancel(task_key)  # type: ignore # syntactic sugar
406        return func
407
408    if callable(key):  # @remote_task without parentheses
409        func = key  # key is actually the function
410        return decorator(func)
411    # @remote_task(...) was used
412    decorator.forgot_to_call = True  # type: ignore[reportFunctionMemberAccess]
413    return decorator

Decorator for methods: Expose the method as a long-running task to the frontend.

A task is a "non-blocking" method that runs concurrently with the backend logic. The frontend can cancel the task at any time, so you should also implement a @remote_task_cancel method to cancel the task.

Arguments:
  • key: unique key (matching the frontend key) to identify the task. If None, defaults to the method name.
def find_remote_tasks(cls: type) -> dict[str, Callable]:
416def find_remote_tasks(cls: type) -> dict[str, Callable]:
417    """
418    Find all remote tasks in a class.
419
420    Returns a dictionary of task keys to the function.
421    """
422    tasks: dict[str, Callable] = {}
423    for attr_name in dir(cls):
424        try:
425            attr = getattr(cls, attr_name)
426        except AttributeError:
427            continue
428        if isinstance(attr, property):
429            continue
430        if callable(attr) and hasattr(attr, "remote_task"):
431            tasks[attr.remote_task] = attr  # type: ignore[reportFunctionMemberAccess]
432    return tasks

Find all remote tasks in a class.

Returns a dictionary of task keys to the function.

def remote_task_cancel(key: str) -> Callable[[F], F]:
435def remote_task_cancel[F: Callable](key: str) -> Callable[[F], F]:
436    """
437    Decorator for methods: Expose the method as a task-canceller to the frontend.
438
439    A task-canceller is a method that cancels a running task.
440    The method `f` decorated with `@remote_task` has a corresponding cancel decorator `@f.cancel`:
441    ```python
442    @remote_task("MY_TASK")
443    async def my_task(self): ...
444
445    @my_task.cancel
446    async def cancel_my_task(self): ...
447    ```
448
449    Args:
450        key: unique key (matching the frontend key) to identify the task
451    """
452
453    def decorator(func: F) -> F:
454        func.remote_task_cancel = key  # type: ignore
455        return func
456
457    decorator.forgot_to_call = True  # type: ignore[reportFunctionMemberAccess]
458    return decorator

Decorator for methods: Expose the method as a task-canceller to the frontend.

A task-canceller is a method that cancels a running task. The method f decorated with @remote_task has a corresponding cancel decorator @f.cancel:

@remote_task("MY_TASK")
async def my_task(self): ...

@my_task.cancel
async def cancel_my_task(self): ...
Arguments:
  • key: unique key (matching the frontend key) to identify the task
def find_remote_task_cancellers(cls: type) -> dict[str, Callable]:
461def find_remote_task_cancellers(cls: type) -> dict[str, Callable]:
462    """
463    Find all remote task-cancellers in a class.
464
465    Returns a dictionary of task-canceller keys to the function.
466    """
467    cancellers: dict[str, Callable] = {}
468    for attr_name in dir(cls):
469        try:
470            attr = getattr(cls, attr_name)
471        except AttributeError:
472            continue
473        if isinstance(attr, property):
474            continue
475        if callable(attr) and hasattr(attr, "remote_task_cancel"):
476            cancellers[attr.remote_task_cancel] = attr  # type: ignore[reportFunctionMemberAccess]
477    return cancellers

Find all remote task-cancellers in a class.

Returns a dictionary of task-canceller keys to the function.