Sleeping whether or not async

I’d like to be able to write some utility routines that can be called either within a ‘normal’ environment or within an async environment. I need the utility routines to be able to sleep – they scrape web sites and I don’t want to overload the sites.

Is there any way to write code to sleep which will work in both environments?

Related: is there some way to tell when you are running within a trio.run()?

If you’re in a coroutine function, you have to use an async sleep function. Likewise, if you’re in a synchronous function, you cannot use the async sleep functions.

To answer your second question, you can either use the sniffio library to detect which async event loop you’re running in, or you could try calling trio.lowlevel.current_trio_token() which will raise a RuntimeError if you’re not running trio.

1 Like