Skip to content

Commit

Permalink
feat($async): support decorate function with @async_function
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnymillergh committed Sep 7, 2022
1 parent 8f2ddea commit 44a0a7e
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
40 changes: 40 additions & 0 deletions python_boilerplate/common/asynchronization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import functools
from typing import Callable

from loguru import logger

from python_boilerplate.configuration.thread_pool_configuration import (
done_callback,
executor,
)


def async_function(func: Callable):
"""
The decorator to run function in thread pool. The return value of decorated function will be
`concurrent.futures._base.Future`.
Usage: decorate the function with `@async_function`
https://stackoverflow.com/questions/37203950/decorator-for-extra-thread
:param func: function to run in thread pool
"""

@functools.wraps(func)
def wrapped(*arg, **kwarg):
if arg and not kwarg:
submitted_future = executor.submit(func, *arg)
elif not arg and kwarg:
submitted_future = executor.submit(func, **kwarg)
elif arg and kwarg:
submitted_future = executor.submit(func, *arg, **kwarg)
else:
submitted_future = executor.submit(func)
submitted_future.add_done_callback(done_callback)
logger.debug(
f"Submitted future task {submitted_future} to run [{func.__qualname__}()] asynchronously"
)
return submitted_future

return wrapped
66 changes: 66 additions & 0 deletions tests/common/test_asynchronization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from concurrent.futures import Future
from time import sleep

import arrow
from loguru import logger

from python_boilerplate.common.asynchronization import async_function


@async_function
def an_async_function(param1: str, param2: str):
sleep(1)
logger.info(f"Function's param1={param1}, param2={param2}")
return f"Hello, got param1={param1}, param2={param2}"


@async_function
def another_async_function_without_args():
sleep(1)
logger.info(f"Hello from {another_async_function_without_args.__qualname__}")


def test_async_function_expected_no_errors():
try:
a_future: Future = an_async_function(
arrow.now().__str__(), arrow.now().shift(days=-1).__str__()
)
assert a_future is not None
result = a_future.result()
assert len(result) > 0
logger.info(f"Got future result: {result}")
except Exception as ex:
assert False, f"{an_async_function} raised an exception {ex}"


def test_async_function_pass_kwarg_expected_no_errors():
try:
a_future: Future = an_async_function(
param1=arrow.now().__str__(), param2=arrow.now().shift(days=-1).__str__()
)
assert a_future is not None
result = a_future.result()
assert len(result) > 0
logger.info(f"Got future result: {result}")
except Exception as ex:
assert False, f"{an_async_function} raised an exception {ex}"


def test_async_function_pass_arg_kwarg_expected_no_errors():
try:
a_future: Future = an_async_function(
arrow.now().__str__(), param2=arrow.now().shift(days=-1).__str__()
)
assert a_future is not None
result = a_future.result()
assert len(result) > 0
logger.info(f"Got future result: {result}")
except Exception as ex:
assert False, f"{an_async_function} raised an exception {ex}"


def test_another_async_function_without_args_expected_no_errors():
try:
another_async_function_without_args()
except Exception as ex:
assert False, f"{another_async_function_without_args} raised an exception {ex}"

0 comments on commit 44a0a7e

Please sign in to comment.