No swap function in Python?

Carlos Ribeiro cribeiro at
Fri Jun 1 01:12:05 CEST 2001

That's Bjorn Pettersen way of showing Ben Wolfson that locals aren't 

At 16:55 31/05/01 -0600, Bjorn Pettersen wrote:
>def foo():
>    a = 10
>    b = 5
>    swap(a=a, b=b)
>    print a,b
>still prints 10 5...
>real-locals-aren't-writable'ly y'rs
>-- bjorn

Why is it so? Because locals get accelerated by the compiler. Variables 
local to the context of a single function aren't bound by name. They end up 
being bound by indexes to the local stack frame. As the pointer is fixed at 
compile time, it is impossible to swap() them.

This small demo point out that the problem is in truth much more complex 
than simply providing a swap statement. I sincerely doubt that we can come 
up with a simple implementation without changing the way locals are 
handled. In fact, there are other cases that were not explored at all:

- swap global-global
- swap local-local
- swap global-local

This is going to be a mess :-)

Carlos Ribeiro

More information about the Python-list mailing list