converting from perl: variable sized unpack

phil hunt philh at comuno.freeserve.co.uk
Mon Jul 16 07:52:36 EDT 2001


On 16 Jul 2001 00:55:48 GMT, Quinn Dunkan <quinn at yak.ugcs.caltech.edu> wrote:
>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.

On the occasions when this matters, you can simply say:

   list = string.spolit(line)
   if list != 6: ...error code here...

However, im my experience, most of the time you don't want to do this,
most of the time, if there are too few or many values, you weant the
software to "do its best". This goes for lots of things; IMO if you
access a list or dictionary with a non-existant index it should
return a value such as None, instead of raising an exception.


-- 
#===== Philip Hunt == philh at comuno.freeserve.co.uk ======#
    Herbivore: effort-free public key encryption. See:
<http://www.vision25.demon.co.uk/oss/herbivore/intro.html>
        ** First software release coming soon! **






More information about the Python-list mailing list