run_coro_thread¶
-
privex.helpers.asyncx.
run_coro_thread
(func: callable, *args, **kwargs) → Any[source]¶ Run a Python AsyncIO coroutine function within a new event loop using a thread, and return the result / raise any exceptions as if it were ran normally within an AsyncIO function.
Caution
If you’re wanting to run a coroutine within a thread from an AsyncIO function/method, then you should use
run_coro_thread_async()
instead, which usesasyncio.sleep()
while waiting for a result/exception to be transmitted via a queue.This allows you to run and wait for multiple coroutine threads simultaneously, as there’s no synchronous blocking wait - unlike this function.
This will usually allow you to run coroutines from a synchronous function without running into the dreaded “Event loop is already running” error - since the coroutine will be ran inside of a thread with it’s own dedicated event loop.
Example Usage:
>>> async def example_func(lorem: int, ipsum: int): ... if lorem > 100: raise AttributeError("lorem is greater than 100!") ... return f"example: {lorem + ipsum}" >>> run_coro_thread(example_func, 10, 20) example: 30 >>> run_coro_thread(example_func, 3, ipsum=6) example: 9 >>> run_coro_thread(example_func, lorem=40, ipsum=1) example: 41 >>> run_coro_thread(example_func, 120, 50) File "", line 2, in example_func if lorem > 100: raise AttributeError("lorem is greater than 100!") AttributeError: lorem is greater than 100!
Creates a new
threading.Thread
with the targetcoro_thread_func()
(viarun_coro_thread_base()
), passing the coroutinefunc
along with the passed positionalargs
and keywordkwargs
, which creates a new event loop, and then runsfunc
within that thread event loop.Uses the private
queue.Queue
threading queue_coro_thread_queue
to safely relay back to the calling thread - either the result from the coroutine, or an exception if one was raised while trying to run the coroutine.- Parameters
func (callable) – A reference to the
async def
coroutine function that you want to runargs – Positional arguments to pass-through to the coroutine function
kwargs – Keyword arguments to pass-through to the coroutine function
- Return Any coro_res
The result returned from the coroutine
func