It seems there is a general need in some use cases that async and non async code according to https://peps.python.org/pep-0492/ in python should be able to work together in a straightforward way.
It should be possible:
- To call an async function from a synchronous context
- To call a synchronous function from an asynchronous context
without having to bother about the complex infrastructure problems involved and the design decisions that have been made by the inventors of the async/await functionality in python which call for such complexities.
see e.g.
- Call async function from sync function, while the synchronous function continues : Python
- Why do most asyncio examples use loop.run_until_complete()?
- https://www.joeltok.com/posts/2021-02-python-async-sync/
- https://bbc.github.io/cloudfit-public-docs/asyncio/asyncio-part-5.html
Hiding the complexity of the answers with some "syntactic sugar" is what i am looking for.
There is e.g.
A) https://github.com/ccorcos/syncify/blob/master/syncify/syncify.py since 2014 - but that project has no stars as of 2022-12.
B) See also https://gist.github.com/phizaz/20c36c6734878c6ec053245a477572ec for a gist proposing a similar approach.
C) https://www.aeracode.org/2018/02/19/python-async-simplified/ which points to https://github.com/django/asgiref/blob/main/asgiref/sync.py
D) there is https://asyncer.tiangolo.com/ which has almost a thousand stars.
I tried
A
whith python 3.10 and got the error message:
def async(*args):
^^^^^
SyntaxError: invalid syntax
CRITICAL: Exiting due to uncaught exception <class 'SyntaxError'>
the gist B)
with:
scite_entry=force_sync(doi_obj.asScite)()
and got the error message:
RuntimeError: This event loop is already running
which leads to the question:
so it's not useable as a general syntactic sugar hiding the complex details - you have to know in which context you are running your code.
asgiref C) and get the error message:
RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
so it's again not useable as a general syntactic sugar hiding the complex details - you have to know in which context you are running your code.
the tiangolo library D)
with a single line:
scite_entry=syncify(doi_obj.asScite)()
and got the error message:
RuntimeError: This function can only be run from an AnyIO worker thread
so it's not generally useable.
What would be a general approach that hides the involved complex infrastructure problems and might make it into a PEP in the future?