[Python Wpg] Swapping object attribute values

Sydney Weidman syd at plug.ca
Thu Feb 26 08:15:58 EST 2009


I like the way you can swap the values of variables in Python by saying
something like:

a, b = b, a

but suppose I want a function that will swap arbitrary attributes on an
object. Could I code that using the tuple unpacking assignment style? I
ended up doing this:

    def transpose(self, from_attr, to_attr):
        """Transpose the co-ordinates from one axis to another"""
        to_val = getattr(self,to_attr)
        setattr(self, to_attr, getattr(self, from_attr))
        setattr(self, from_attr, to_val)

Is there a more compact, readable way to do this?

Regards,
Syd





More information about the Winnipeg mailing list