From b019aedd033ed6d7a59403b2067d321dfcea67fe Mon Sep 17 00:00:00 2001 From: Eren Yurtcu <137696300+erenyurtcu@users.noreply.github.com> Date: Mon, 28 Oct 2024 13:12:56 +0300 Subject: [PATCH] Create awaitme_ismeteren_yurtcu.py --- Week05/awaitme_ismeteren_yurtcu.py | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Week05/awaitme_ismeteren_yurtcu.py diff --git a/Week05/awaitme_ismeteren_yurtcu.py b/Week05/awaitme_ismeteren_yurtcu.py new file mode 100644 index 00000000..e0d3c35b --- /dev/null +++ b/Week05/awaitme_ismeteren_yurtcu.py @@ -0,0 +1,34 @@ +import asyncio + +def awaitme(f): + """ + A decorator to handle both synchronous and asynchronous functions seamlessly. + + If the decorated function is asynchronous, it awaits the function's result. + If the decorated function is synchronous, it directly returns the result. + + Args: + f (function): The function to be decorated. It can be either synchronous or asynchronous. + + Returns: + function: An asynchronous wrapper that handles both sync and async functions gracefully. + """ + async def wrapper(*args, **kwargs): + """ + Wrapper function that calls the original function and checks whether it's a coroutine. + + If the result is a coroutine, it awaits the result. Otherwise, it returns the result directly. + + Args: + *args: Positional arguments to pass to the original function. + **kwargs: Keyword arguments to pass to the original function. + + Returns: + Any: The result of the original function, either awaited (if async) or direct (if sync). + """ + fn = f(*args, **kwargs) + if asyncio.iscoroutine(fn): + return await fn + return fn + + return wrapper