structured unpacking assignments
jcarlson at uci.edu
Fri Oct 22 20:47:14 CEST 2004
> mylist = [('the', 'article'), ('house', 'noun'), ('run', 'verb')]
> for n,(part,word) in enumerate(mylist):
> word_array[n] = Usage(part, word)
> This actually feels a lot like lisp's macro destructure feature.
> Taking it a bit farther:
> [adapted from "Common Lisp", G.L. Steele Jr. 2nd Ed., Digital Press 1990]:
> ((mouth, eye1, eye2),
> ((fin1, len1),(fin2, len2)),
> tail) = \
> ((m, eyes, eyes),
> ((f1, count_scales(f1)), (f2, count_scales(f2))),
> Now, I think that pythoneers often use bare list/tuple structures
> when a class would be much clearer, and I don't recommend managing halibut
> data as in the example. But the first example seems quite clear and natural.
Sometimes yes, sometimes no. In the case of transferring data over a
network connection, there must be some encoding and decoding going on.
Tuples of simple data are easily packed via struct.pack(), or if one is
being ambitous with their data (fixed order, but with values of
arbitrary size), pickle.dumps().
Struct will generally be faster, but you lose flexibility (you have to
change your packing and unpacking calls). Pickle is more general, but
if you are using classes, then you must make sure that the class
definitions are both in-scope.
For those who use classes for C-struct-like named attributes, tuples are
sufficient for passing over a network. For those who use classes with
full functionality, sometimes instance.totuple() and cls.fromtuple() are
better than relying on class pickling.
> Does anyone else have illustrious examples of structured unpacking?
None that I can show, but I do use this kind of thing.
One thing to remember is that the more items in your structure, the
slower it will run. Probably not a deal breaker, but something one
should be aware of.
More information about the Python-list