Sync / async sleep in function

I’m trying to figure out if it’s possible to create a function of the form:

def example(sleep_fn=time.sleep):
    a = sample()
    sleep_fn(60)
    b = sample( )
   # do things with b -a

where sleep_fn could be the default time.sleep() for running from a thread, and asyncio.sleep() for calling example in a coroutine.

If this is possible, I’m unable to figure out the syntax.

1 Like

Sorry, it isn’t. This is the function colouring problem. The problem is, you don’t just want to call asyncio.sleep - you have to await it, and that means the calling function has to be an async function - which is kinda like a generator in that it can be set aside in the middle and subsequently resumed.

Your best options are either (a) make two functions, synchronoous and asynchronous, and have your caller choose; or (b) make an async function, with a sync wrapper that spins up a temporary event loop for it to run in.

3 Likes