Package: fast-async
Fast AsyncA thread based, asynchronous programming framework built for Python.
Designed and optimized for speed.Asyncio, the go-to asynchronous programming framework for Python, uses
a single-threaded event loop to achieve concurrency. Although this prevents
unnecessary computational overheads and race conditions, it is inherently not
as fast as threads (even with inefficiencies brought along with GIL). In some
scenarios where speed is of utmost importance and where computational resources
are abundant, then it makes sense to use a multi-threading approach to concurrency.Fast Async is a high-level API for Pythonthreads, providing users with the
ability toawaitasynchronous code, and other features such as event-driven,
pubsub model (similar to Javascript'sPromise.then()). It aims to serve as
an alternative to asyncio, for users who require faster execution speed.InstallationRunpip install fast-asyncRunning locallyClone the repository and make the working directorysrc/.Alternatively, extract the foldersrc/fast_async.BenchmarksScenario (sample.py)A long-running network request and an expensive operation is executed asynchronouslyResultfast-asyncis, on average, almost 50% faster thanasynciodue to
asyncio executing the two tasks almost sequentially whilst fast-async leverages threads
to execute them in parallel.FAQWhen to use fast-asyncFast-async should be used when execution speed is a higher priority.
For example, uploading each frame of a video stream to a remote server.
For cases where execution speed is not important, or when well-written code
make the speed differences negligible, asyncio is preferred.What about ThreadPoolExecutor?ThreadPoolExecutoris a Python built-in class that offers some of the
same functionalities as fast-async, namely the ability to wait for tasks, and
limiting threads to conserve resources. However, fast-async is more feature-rich,
such as the event-driven model (subscribers and callbacks) and various utility functions
that mirror certain useful functionalities from other languages (such as JavaScript).
Fast-async is designed to enhance developer experience when working with threads, by
offering an easy-to-use interface and minimal pre-requisite knowledge.DocumentationDecorators@make_asyncMake a function asynchronous. Functions that are decorated withmake_asyncwill return an object of typeAsyncTaskAside from its type, decorated functions can be treated as a normal function.
This means arguments can be passed in, much like a regular function.Exceptions raised within the decorated function will be caught and re-thrown
in the caller thread.Example:fromfast_asyncimportmake_async@make_asyncdefhello(message):print("hello world")returnmessage# Awaits hello to finish executingreturn_val=hello("hello world").wait()# Prints "hello world"print(return_val)ClassesPackage: fast_async.types.tasksclass AsyncTask(func: Callable, *args, **kwargs)Attributesfunc: A function orCallable.*args: Non-keyworded arguments for func**kwargs: Keyworded arguments for funcstatus: Current status of func (pending, success, failure)result: Return value of functhread:Threadthat func is being ran onexception: First caughtExceptionraised in funcMethodsrun()Runsfuncon a child thread, returnsNone.wait()Awaitsfuncto finish executing (blocks the caller thread),
returns the return value offunc.subscribe(on_success: Callable, on_failure: Callable, blocks: bool = False)Subscribes success and failure callbacks that is invoked when task is
finished executing or raised an exception. Optional blocks argument
controls whether subscribe blocks the caller thread (by default subscribe does not block)Functionsset_max_threads(num: int): NoneSet the max number of threads available to be consumed by tasks.
Default is 64 threads. Useful when wanting to dynamically scale
usage.Example:fromfast_asyncimportset_max_threadsset_max_threads(3)# Only allows a maximum of 3 concurrent threadsawait_all(tasks: List[AsyncTask]): ListWaits for all tasks in thetaskslist to finish executing, or
when a task fails, then the function will immediately raise an exception and exit.Returns a list of results corresponding to the list of tasks provided.Similar to JavaScript'sPromise.all()Example:fromfast_asyncimportmake_asyncfromfast_async.utilsimportawait_all@make_asyncdeffunc1():return1@make_asyncdeffunc2():return2await_all([func1(),func2()])# Will return [1, 2]await_first(tasks: List[AsyncTask]): AnyWaits for the first task intaskslist to finish executing
and immediately returns the result. If all tasks fail, then the first
failed task is raised in an exception.Returns the result of the first successful task.Similar to JavaScript'sPromise.race()Examplefromfast_asyncimportmake_asyncfromfast_async.utilsimportawait_firstimporttime@make_asyncdeffunc1():time.sleep(1)return1@make_asyncdeffunc2():time.sleep(2)return2await_first([func1(),func2()])# Will return 1, because func1 finishes first