need help on need help on generator...

Craig Ringer craig at postnewspapers.com.au
Sat Jan 22 05:17:10 EST 2005


On Sat, 2005-01-22 at 17:46 +0800, I wrote:

> I'd be interested to know if there's a better solution to this than:
> 
> .>>> inpath = '/tmp/msg.eml'
> .>>> infile = open(inpath)
> .>>> initer = iter(infile)
> .>>> headers = []
> .>>> for line in initer:
> ....     if not line.strip():
> ....             break
> ....     headers.append(tuple(line.split(':',1)))
> .>>> data = ''.join(x for x in initer)
> 
> because that seems like a pretty ugly hack (and please ignore the
> variable names). Perhaps a way to get the file to seek back to the point
> last read from the iterator when the iterator is destroyed?

And now, answering my own question (sorry):

Answer: http://tinyurl.com/6avdt

so we can slightly simplify the above to:

.>>> inpath = '/tmp/msg.eml'
.>>> infile = open(inpath)
.>>> headers = []
.>>> for line in infile:
....     if not line.strip():
....             break
....     headers.append(tuple(line.split(':',1)))
.>>> data = ''.join(x for x in infile)

at the cost of making it less clear what's going on and having someone
later go "duh, why isn't he using read() here instead" but can't seem to
do much more than that.

Might it be worth providing a way to have file objects seek back to the
current position of the iterator when read() etc are called? If not, I
favour the suggestion in the referenced post - file should probably fail
noisily, or at least emit a warning.

What are others thoughts on this?

-- 
Craig Ringer




More information about the Python-list mailing list