awaitable_class¶
-
privex.helpers.asyncx.
awaitable_class
(cls: Type[T]) → Type[T][source]¶ Wraps a class, allowing all async methods to be used in non-async code as if they were normal synchronous methods.
Example Usage
Simply decorate your class with
@awaitable_class
(no brackets! takes no arguments), and once you create an instance of your class, all of your async methods can be used by synchronous code as-if they were plain functions:>>> from privex.helpers import awaitable_class >>> >>> @awaitable_class >>> class ExampleAsyncCls: >>> async def example_async(self): >>> return "hello async world" >>> >>> def example_sync(self): >>> return "hello non-async world" >>>
NOTE - You can also wrap a class without using a decorator - just pass the class as the first argument like so:
>>> class _OtherExample: ... async def hello(self): ... return 'world' >>> OtherExample = awaitable_class(_OtherExample)
If we call
.example_async()
on the above class from a synchronous REPL, it will return'hello async world'
as if it were a normal synchronous method. We can also call the non-async.example_sync()
which works like normal:>>> k = ExampleAsyncCls() >>> k.example_async() 'hello async world' >>> k.example_sync() 'hello non-async world'
However, inside of an async context (e.g. an async function),
awaitable_class
will be returning coroutines, so you shouldawait
the methods, as you would expect when dealing with an async function:>>> async def test_async(): >>> exmp = ExampleAsyncCls() >>> return await exmp.example_async() >>> >>> await test_async() 'hello async world'
- Parameters
cls (type) – The class to wrap
- Return type wrapped_class
The class after being wrapped