swapping (was Re: Changing class membership)

Alex Martelli aleaxit at yahoo.com
Fri Oct 6 11:59:14 EDT 2000


<matthias.oberlaender at daimlerchrysler.com> wrote in message
news:8r1ng6$hef$1 at news.sns-felb.debis.de...
    [snip]
> def transmogrify(x, y):
> # Exchanges the properties of instances x and y.
> # The identity of x and y remain the same. But their
> # class membership and all their attributes get exchanged.
>   h = x.__dict__
>   x.__dict__ = y.__dict__
>   y.__dict__ = h
>   h = x.__class__
>   x.__class__ = y.__class__
>   y.__class__ = h

Swapping any two "thingies" is easier than this in Python:

def transmogrify(x, y):
    x.__dict_, y.__dict__ = y.__dict__, x.__dict__
    x.__class_, y.__class__ = y.__class__, x.__class__

In general, the Python swap idiom is
    a, b = b, a
or, of course:
    a.something, b.whatever = b.whatever, a.something
etc, although the idiom of
    temp = a
    a = b
    b = temp
(mutuated from languages without tuple packing/unpacking
abilities:-) will also work, of course (less elegant, IMHO).


Alex






More information about the Python-list mailing list