Skip to content

Commit 651898a

Browse files
authored
Merge pull request #663 from erenyurtcu/patch-8
Create awaitme_ismeteren_yurtcu.py
2 parents a7c7747 + b019aed commit 651898a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Week05/awaitme_ismeteren_yurtcu.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import asyncio
2+
3+
def awaitme(f):
4+
"""
5+
A decorator to handle both synchronous and asynchronous functions seamlessly.
6+
7+
If the decorated function is asynchronous, it awaits the function's result.
8+
If the decorated function is synchronous, it directly returns the result.
9+
10+
Args:
11+
f (function): The function to be decorated. It can be either synchronous or asynchronous.
12+
13+
Returns:
14+
function: An asynchronous wrapper that handles both sync and async functions gracefully.
15+
"""
16+
async def wrapper(*args, **kwargs):
17+
"""
18+
Wrapper function that calls the original function and checks whether it's a coroutine.
19+
20+
If the result is a coroutine, it awaits the result. Otherwise, it returns the result directly.
21+
22+
Args:
23+
*args: Positional arguments to pass to the original function.
24+
**kwargs: Keyword arguments to pass to the original function.
25+
26+
Returns:
27+
Any: The result of the original function, either awaited (if async) or direct (if sync).
28+
"""
29+
fn = f(*args, **kwargs)
30+
if asyncio.iscoroutine(fn):
31+
return await fn
32+
return fn
33+
34+
return wrapper

0 commit comments

Comments
 (0)