itertools suggestion

Magnus Lie Hetland mlh at furu.idi.ntnu.no
Fri Feb 21 22:54:31 EST 2003


Some things that might be useful (with rather arbitrary names)

  iatom(foo)       -- an iterator that returns foo
  iappend(it, foo) -- an iterator that exhausts it and then returns
                      foo

The latter could, of course, be achieved with

  chain(it, iatom(foo))

if chain is adopted. (Odd that it is documented but not included... :)

The motivation for this is code like this:

  pars = []
  par = []
  for line in iappend(open('file.txt'), '\n'):
      if not line.strip() and par:
          pars.append(par)
          par = []
      else:
          par.append(line)

The deal here is that there must be an empty line at the end of the
iterator of lines to make sure the code actually processes the last
paragraph (and to avoid code duplication; refactoring out the loop
body would reduce that too, of course).

Just a thought, though -- I'm sure there are other ways of doing this
that may be prettier...

-- 
Magnus Lie Hetland               "Nothing shocks me. I'm a scientist." 
http://hetland.org                                   -- Indiana Jones




More information about the Python-list mailing list