Utilities¶
Various utilities for working with ZyncIO.
- enum Mode(value)¶
ZyncIO execution mode.
Valid values are as follows:
- SYNC = <Mode.SYNC: 'sync'>¶
- ASYNC = <Mode.ASYNC: 'async'>¶
- ZYNC_MODE_CACHE_ATTR: Final = '__zync_cached_mode__'¶
Name of the attribute used by
zyncio.get_modeto cache the mode of aZyncDelegatorobject.You can use this constant to allow caching when defining
__slots__.
- get_mode(obj)¶
Get the
Modeofobj, if it can be determined.If
objis an instance ofzyncio.SyncMixinorzyncio.AsyncMixin, returns the corresponding mode.If
objimplements thezyncio.ZyncDelegatorprotocol, this function will be called recursively with the object returned by the method. The result will be cached onobj, and any intermediate objects, if possible.
- is_sync(obj)¶
Check if
objis a subclass ofzyncio.SyncMixinor implementszyncio.ZyncDelegator[zyncio.SyncMixin]`.- Parameters:
obj (
object) – The object to inspect.- Return type:
- is_async(obj)¶
Check if
objis a subclass ofzyncio.AsyncMixinor implementszyncio.ZyncDelegator[zyncio.SyncMixin].- Parameters:
obj (
object) – The object to inspect.- Return type:
- run_sync(coro)¶
Run a coroutine synchronously.
The coroutine must only
awaitother coroutines, recursively. Awaiting any non-coroutine (such as anasyncio.Future), at any point in the call chain, will cause the function to fail.- Parameters:
coro (
Coroutine[Any,Any,ReturnT_co]) – The sync coroutine to run.- Return type:
- Returns:
The return value of the coroutine.
- make_sync(func)¶
Wrap an async function make it run synchronously using
zyncio.run_sync.This function is useful for overloaded functions and methods, whose signatures can’t be captured properly by
zyncio.zmethodetc.Example
class BaseClient(zyncio.ZyncBase): @overload async def _overloaded_method(self, x: str) -> bytes: ... @overload async def _overloaded_method(self, x: int) -> bool: ... async def _overloaded_method(self, x: str | int) -> bytes | bool: ... class SyncClient(zyncio.SyncMixin, BaseClient): overloaded_method = zyncio.make_sync(BaseClient._overloaded_method) class AsyncClient(zyncio.AsyncMixin, BaseClient): overloaded_method = BaseClient._overloaded_method
If any of your overload signatures use
Self, you may need to define your method outside of the class for type checkers to infer the correct type forSelfin subclasses:class BaseClient(zyncio.ZyncBase): ... ClientT = TypeVar('ClientT', bound=BaseClient) @overload async def overloaded_method(self: ClientT, x: str) -> ClientT: ... @overload async def overloaded_method(self, x: int) -> bool: ... async def overloaded_method(self: ClientT, x: str | int) -> ClientT | bool: ... class SyncClient(zyncio.SyncMixin, BaseClient): overloaded_method = zyncio.make_sync(overloaded_method) class AsyncClient(zyncio.AsyncMixin, BaseClient): overloaded_method = overloaded_method
- Parameters:
func (
async(*P.args,**P.kwargs)->ReturnT_co) – The function to wrap.- Return type:
(*P.args,**P.kwargs)->ReturnT_co