[Python-Dev] PEP 343 - next steps
Nick Coghlan
ncoghlan at gmail.com
Sun Jun 12 05:26:14 CEST 2005
Nick Coghlan wrote:
> Either way, the code generation for the with statement could simply
> emit BLOCK_ASYNC as the first opcode, then ALLOW_ASYNC as the opcode
> immediate preceding SETUP_FINALLY. Correct behaviour in the face of
> asynchronous events is then guaranteed, even for cases where the
> resource is acquired in EXPR, or when __enter__ is written in Python.
Coming up out of the implementation weeds, this can be described as
follows:
"""
Atomic resource acquisition
The resource acquisition line that starts the with statement is
executed atomically. That is, the Python interpreter prevents
asynchronous events and automatic context switches while the resource
is being acquired. Context switches due to the current thread becoming
blocked (e.g. by attempting to acquire a synchronisation lock) will
still occur, avoiding deadlock.
Automatic context switches or asynchronous events that would have
occurred during evaluation of the resource acquisition line are
deferred so that they occur immediately prior to the execution of the
contained suite. This ensures that the acquired resource is still
properly released in the face of an asynchronous exception such as
KeyboardInterrupt.
To avoid blocking exceptions for an extended period, 'expensive'
calculations can be carried out on the line preceding the with
statement, and stored in a local variable for use in the resource
acquisition:
tmp = some_expensive_calculation()
with tmp as rsrc:
# Perform operations with resource
Note that, in this case, the actual resource acquisition should occur
in tmp.__enter__, in order to enjoy the benefits of the atomic
resource acquisition.
"""
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.blogspot.com
More information about the Python-Dev
mailing list