Been looking (again) at XMPP recently. While browsing through existing source code and samples in several languages, there’s one pattern which comes back quite frequently in ‘echobot’ demos: when a message comes in, the to and from attributes are swapped, and the message is sent.
The most common approach is something like (pseudocode):
temp = from
from = to
to = temp
In Python there’s an easier approach though which seems to be unknown to several developers. It uses the multi-assignment/expansion syntax:
from, to = to, from
Basically, the tuple on the right (to, from) is constructed, then expanded to locals ‘from’ and ‘to’.
Just a hint It’s a pretty elegant line of code IMHO.
In case anyone cares Perl has a very similar construct:
($a, $b) = ($b, $a);
Python rules.
In a rather similar way, Python lets you compare more than two values at once, e.g. 1 < x < 100. Most other programming languages would require you to split that into multiple comparisons combined with boolean operators.
Marius: Thanks, didn’t know that one!
If you benchmark it, you’ll find that the first version using the temporary variable is faster than the second version. This isn’t too surprising when you realise that it creates a tuple object then has to pull the values out of the tuple object and finally destroy it.
This isn’t to say that tuple unpacking isn’t useful — if you’ve already got a tuple and you want to assign its items to variables it is a very convenient language feature.
James: I think you’re wrong here (in the case of swapping 2 variables).
The reason is obvious when looking at the opcodes generated by the compiler (which is an optimization of the general system using tuple pack/unpack):
The unoptimized case:
I guess I was wrong for modern versions of Python. It’s good to see that the cleanest looking solution is now the most efficient (and seems to have been since at least 2.4).
…: tmp = a
…: a = b
…: b = a
Not that it matters, but the result of this is a = b, and b = b
Hmh, rather stupid typo Thanks for noticing.