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:
def foo(): yield "something\n" yield "otherthings" stream = IterIO(foo()) 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:
def foo(stream): stream.write("some") stream.write("thing") stream.flush() stream.write("otherthing") iterator = IterIO(foo) print iterator.next() # prints something print iterator.next() # prints otherthing iterator.next() # raises StopIteration
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 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.
0.9 新版功能: sentinel parameter was added.