converting from perl: variable sized unpack

Quinn Dunkan quinn at yak.ugcs.caltech.edu
Sun Jul 15 20:55:48 EDT 2001


On Fri, 13 Jul 2001 23:28:39 -0400, Barry A. Warsaw <barry at digicool.com> wrote:
>    RS>  [f1, f2, f3, f4, f5, f6] = string.split (line)
>
>    RS> but the problem is that line may have fewer than 6 fields on
>    RS> it.  Perl handles this smoothly by leaving the "extra"
>    RS> variables undefined, whereas python raises a ValueError
>    RS> exception.  What I'd like to do is have the extra field
>    RS> variables left as null strings.
>
>Python doesn't work this way, but I've been thinking about writing a
>PEP to make sequence unpacking less strict.

Please don't.  Or if you do, I hope it "lays the issue to rest".  I often use
unpacking from log files, with the assumption that the wrong number of fields
is a parsing error, and should be reported as one, not silently "fixed".  If
you are relying on your log files having the same number of fields, it is an
error if they don't.  If your log files have a variable number of fields, you
should split into a list and pick it apart more carefully.

And that's just for log files, I use this often to unpack tuples, and if I
pass in a non-conformant tuple, that's bad data and should break sooner rather
than later.

But mostly, it's a change that doesn't fix something which is clearly broken
(you could argue either way), but breaks existing code.  Even without that, I
argue that a bad pattern match should throw an exception and not assign None,
just like a bad array index should throw an exception and not assign None.
It's more consistent with the language.



Ruby allows * notation:

a, b, *c = sequence # `c' gets the rest of the sequence

which is cute, but I don't like it.  Just another random "convenient" little
trick to remember.  It's not half as useful as the 1.6 * apply trick.  Let's
go easy on the syntax gimmicks.



More information about the Python-list mailing list