From f76a8a04f5273abee091d4f56adb4daf98d928e5 Mon Sep 17 00:00:00 2001 From: mertdoganaygun <163443178+mertdoganaygun@users.noreply.github.com> Date: Sun, 5 Jan 2025 17:40:30 +0300 Subject: [PATCH] =?UTF-8?q?awaitme=5Fmert=5Fdo=C4=9Fan=5Fayg=C3=BCn.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...awaitme_mert_do\304\237an_ayg\303\274n.py" | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 "Week05/awaitme_mert_do\304\237an_ayg\303\274n.py" diff --git "a/Week05/awaitme_mert_do\304\237an_ayg\303\274n.py" "b/Week05/awaitme_mert_do\304\237an_ayg\303\274n.py" new file mode 100644 index 00000000..62601db2 --- /dev/null +++ "b/Week05/awaitme_mert_do\304\237an_ayg\303\274n.py" @@ -0,0 +1,30 @@ +import asyncio + + +def make_async(func): + """ + A decorator to convert a function into a coroutine. + + If the function is already a coroutine function, it will be awaited. + If the function is synchronous, it will be executed in an executor + within the current event loop or in a new event loop if none is available. + + This ensures compatibility between synchronous and asynchronous + functions in an async context. + + :param func: The target function (can be synchronous or asynchronous). + :type func: Callable + :return: The result of the function execution. + :rtype: Any + """ + + async def wrapper(*args, **kwargs): + if asyncio.iscoroutinefunction(func): + return await func(*args, **kwargs) + try: + loop = asyncio.get_event_loop() + return await loop.run_in_executor(None, func, *args) + except RuntimeError: # No current event loop + return await asyncio.to_thread(func, *args) + + return wrapper