0

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:

  1. To call an async function from a synchronous context
  2. 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.

Hiding the complexity of the answers with some "syntactic sugar" is what i am looking for.

There is e.g.

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?

Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
  • Interesting question! Though I thought at least part of the selling point of async is about making blocking behavior explicit, e.g. the trio manifesto. Why/when do you want to hide this again, seems like you just want sync behavior back? – Sam Mason Dec 26 '22 at 23:25
  • @SamMason - you just want sync behavior back - definitely No. Async functions are just great but i'd love to use them in a non async-context with no hassle. E.g. when both calling the code as part of a webservice where i love the async aspect and via command line where i don't need it and it seems just to hard to integrate the well running async code given the experience shown above. Also the numbers of views of all the questions seem to show that people are looking for solutions to their problem/needs tub there is no proper offer yet. – Wolfgang Fahl Dec 27 '22 at 01:44
  • see https://github.com/WolfgangFahl/pysotsog/commit/c9bb9a9542270844b8bfcff7f7a15195dfdfda59 for a refactoring where i am not using async anymore to overcome the problem – Wolfgang Fahl Dec 27 '22 at 17:46

0 Answers0