Iter IO

Warning

Deprecated since version 0.15: This will be removed in version 1.0.

werkzeug.contrib.iterio

This module implements a IterIO that converts an iterator intoa stream object and the other way round. Converting streams intoiterators requires the greenlet module.

To convert an iterator into a stream all you have to do is to pass itdirectly to the IterIO constructor. In this example we pass ita newly created generator:

  1. def foo():
  2. yield "something\n"
  3. yield "otherthings"
  4. stream = IterIO(foo())
  5. print stream.read() # read the whole iterator

The other way round works a bit different because we have to ensure thatthe code execution doesn’t take place yet. An IterIO call with acallable as first argument does two things. The function itself is passedan IterIO stream it can feed. The object returned by theIterIO constructor on the other hand is not an stream object butan iterator:

  1. def foo(stream):
  2. stream.write("some")
  3. stream.write("thing")
  4. stream.flush()
  5. stream.write("otherthing")
  6. iterator = IterIO(foo)
  7. print iterator.next() # prints something
  8. print iterator.next() # prints otherthing
  9. iterator.next() # raises StopIteration
  • class werkzeug.contrib.iterio.IterIO
  • Instances of this object implement an interface compatible with thestandard Python file object. Streams are either read-only orwrite-only depending on how the object is created.

If the first argument is an iterable a file like object is returned thatreturns the contents of the iterable. In case the iterable is emptyread operations will return the sentinel value.

If the first argument is a callable then the stream object will becreated and passed to that function. The caller itself however willnot receive a stream but an iterable. The function will be executedstep by step as something iterates over the returned iterable. Eachcall to flush() will create an item for the iterable. Ifflush() is called without any writes in-between the sentinelvalue will be yielded.

Note for Python 3: due to the incompatible interface of bytes andstreams you should set the sentinel value explicitly to an emptybytestring (b'') if you are expecting to deal with bytes asotherwise the end of the stream is marked with the wrong sentinelvalue.

New in version 0.9: sentinel parameter was added.