No swap function in Python?

Carlos Ribeiro cribeiro at mail.inet.com.br
Thu May 31 19:12:05 EDT 2001


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

At 16:55 31/05/01 -0600, Bjorn Pettersen wrote:
>But...
>
>def foo():
>    a = 10
>    b = 5
>    swap(a=a, b=b)
>    print a,b
>
>foo()
>
>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