hello tulip list, when porting the python-mpd2 library[1], i tried to port functions that originally worked like this:
>>> for song in client.listall():
... print(song)
first song
second song
the trivial port, especially with small responses or protocols where
you can retrieve the items only when the complete response is there,
would be
>>> for song in (yield from client.listall()):
... print(song)
. most applications would want to use this kind of interface, as it is
straightforward -- but it delays the execution of the loop until all the
results are there. my current approach is implementing what i'm calling
MultilineFuture (for historical reasons, if it were to be used more
widely i'd probably call it ListlikeFuture) that can be used as above,
but also supports the alternative usage
>>> for cursor in (yield from client.listall().lines):
... song = yield from cursor
... print(song)
that has the same effect but starts printing earlier.
the fulfilling side of the future does not do `future.set_result(["first
song", ...])`, but does
>>> multiline = MultilineFuture()
>>> multiline.send_line("first song")
>>> multiline.send_line("second song")
>>> multiline.set_completed()
. i think the design works well for these applications; the only
shortcoming i see is that one response always needs to be held back, as
the StopIteration for the `for` loop needs to be raised in
`.lines.__next__` and not in `yield from`.
my questions now are:
* is there an established pattern already in place that could do this /
did i reinvent the wheel?
* is there a better way than keeping back one item to make the loop stop
at the right time? (short of coming up with non-python3.4 syntax like
`for song yield from ...`)
* would such a pattern be a useful addition to the common mechanisms
used in asyncio?
* do you see the need for more features in such a mechanism (eg a
`for i, cursor in (yield from client.listall().lines_enumerated)` for
progress indicators)?
i would appreciate your feedback
chrysn
[1] https://github.com/Mic92/python-mpd2/issues/30
--
To use raw power is to make yourself infinitely vulnerable to greater powers.
-- Bene Gesserit axiom
signature.asc
Description: Digital signature
