Code block literals

Lulu of the Lotus-Eaters mertz at gnosis.cx
Sat Oct 11 00:04:35 EDT 2003


Alex Martelli <aleaxit at yahoo.com> wrote previously:
|> xreadlines()? What kind of naming convention is that: :)
|An obsolete one (to go with 'xrange').  Since about 3 years, the
|correct Python spelling is just "for line in file("input.txt"):" .

I would use the reduced form as well, nowadays.  But that fails to
highlight the contrast between iterating over lines, and iterating over
bytes, words, etc.

Likewise with dictionaries, btw:

    >>> for x in {1:2, 3:4}.iterkeys(): print x,
    ...
    1 3
    >>> for x in {1:2, 3:4}.itervalues(): print x,
    ...
    2 4
    >>> for x in {1:2, 3:4}.iteritems(): print x,
    ...
    (1, 2) (3, 4)
    >>> for x in {1:2, 3:4}: print x,
    ...
    1 3

The first and last forms do the same thing; but the first stands out in
contrast with the middle ones better.  If you might be using the
different forms in the same app, being more explicit is likely to be
worthwhile.  In this respect, Alex' likely retort that it's not really
more explicit is wrong.

Of course, in the above case, I think the wrong choice was made.  To me,
'for x in dct' should iterate over items.  This is a case where
"practicality beats purity" was given more weight than "beautiful is
better than ugly".  That is:  I understand the use case, but it offends
my semantic aesthetics.

|def eachbyte(seq):
|def eachword(seq):
|def eachblock(afile, N):

Those are OK.  But none of them quite do what xreadlines.xreadlines()
does for lines.  That is, an iterator over the characters or words in a
file should probably perform moderately large reads, and yield properly
parcelled chunks from the larger read.  Moderately large here means,
say, 4k or 8k--enough to match sector/block sizes of typical disks and
filesystems, but not megabytes.

Personally, I like the aesthetics of methods on file objects (or on
objects that proxy files, and act a lot like actual file objects).  But
functions are fine too... and it's not hard to write either style if I
want too.

Yours, Lulu...

--
mertz@  | The specter of free information is haunting the `Net!  All the
gnosis  | powers of IP- and crypto-tyranny have entered into an unholy
.cx     | alliance...ideas have nothing to lose but their chains.  Unite
        | against "intellectual property" and anti-privacy regimes!
-------------------------------------------------------------------------






More information about the Python-list mailing list