[Python-ideas] Async context managers and iterators with tulip

Nick Coghlan ncoghlan at gmail.com
Sat Dec 22 10:14:59 CET 2012


On Sat, Dec 22, 2012 at 4:17 PM, guido.van.rossum
<python-checkins at python.org> wrote:
> +- We might introduce explicit locks, though these will be a bit of a
> +  pain to use, as we can't use the ``with lock: block`` syntax
> +  (because to wait for a lock we'd have to use ``yield from``, which
> +  the ``with`` statement can't do).

Actually, I just realised that the following can work if the async
lock is defined appropriately:

    with yield from async_lock:
        ...

The secret is that async_lock would need to be a coroutine rather than
a context manager. *Calling* the coroutine would acquire the lock
(potentially registering a callback that is scheduled when the lock is
released) and return a context manager that released the lock. The
async_lock itself wouldn't be a context manager, so you'd get an
immediate error if you left out the "yield from".

We'd be heading even further down the path of
two-languages-for-the-price-of-one if we did that, though (by which I
mean the fact that async code and synchronous code exist in parallel
universes - one, more familiar one, where the ability to block is
assumed, as is the fact that any operation may give concurrent code
the chance to execute, and the universe of Twisted, tulip, et al,
where possible suspension points are required to be explicitly marked
in the function where they occur).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list