No swap function in Python?

Skip Montanaro skip at pobox.com
Thu May 31 16:10:11 EDT 2001


    me>     LOAD_FAST b
    me>     LOAD_FAST a
    me>     STORE_FAST b
    me>     STORE_FAST a
    ...
    Gawain> Furthermore, as Aahz Maruch alludes to in another follow-up
    Gawain> post, an "atomic" swap might also be useful when writing
    Gawain> multi-threaded applications.

To get true atomicity (at the Python VM level) you'd have to define a new
byte code for such an operation.  Furthermore, a swap bytecode would have to
work with a fixed number of arguments (typically two) and would have to be
exposed as a statement or at least an operator (hey, once they finish
deprecating <> as a comparison operator, we could reuse it as the swap
operator <wink> - wouldn't that work wonders for Mailman!).

Finally, note that swap(a,b) is just a special case of the current tuple
pack/unpack operation, so you'd add no new functionality to the language
aside from the atomic nature of the swap - and then only if you added the
new byte code instead of implementing it as a series of two loads and two
stores.  It's not clear that with all the stuff you'd need to do that it
would be worthwhile, though if the atomicity argument is that important to
you, then make your case to Guido.

-- 
Skip Montanaro (skip at pobox.com)
(847)971-7098




More information about the Python-list mailing list