Code: Select all
async
Ich suche daher eine run-Funktion mit der folgenden Signatur:
Code: Select all
def run(coro: Coroutine[Any, Any, _ReturnT]) -> _ReturnT: ...
Code: Select all
run1 = asyncio.run
Code: Select all
def sync_f():
return run(async_f())
Um dies zu sehen, stellen Sie sich ein anderes (Sync-)Modul vor, das auf sync_f aufbaut, um dies zu tun andere synchrone Dinge:
Code: Select all
def sync_g():
print("Doing some synchronous things")
res = sync_f()
print("Doing some other synchronous things")
return res
Code: Select all
async def async_h():
print("Doing some asynchronous things")
res = sync_g()
print("Doing some other asynchronous things")
return res
Ich habe versucht, mit meiner Definition von run etwas intelligenter zu sein, um herauszufinden, ob Derzeit läuft eine übergeordnete Schleife, und zwar meine Coroutine in das:
Code: Select all
def run2(coro: Coroutine[Any, Any, _ReturnT]) -> _ReturnT:
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(coro)
else:
return loop.run_until_complete(coro)
Was Sinn macht, aber ich konnte nichts finden, das die aktuelle Ausführung verwenden würde (so etwas wie loop.wait_until_complete(coro)).
Gibt es keine Möglichkeit, eine asynchrone Funktion in eine normale Funktion zu packen, die genau wie eine synchrone Funktion funktioniert? ohne die Implementierung zu haben Detail der asynchronen Version, die in die höheren Kontexte gelangt?