Request for elucidation: enhanced generators
Duncan Booth
duncan.booth at invalid.invalid
Wed Sep 20 09:00:57 EDT 2006
"Ben Sizer" <kylotan at gmail.com> wrote:
>> If you have no use case for this you are, as always, perfectly free to
>> ignore it, as the majority of Python users may well choose to do. Your
>> existing generators should continue to work.
>
> But do you have an example of such a use case? That's what I'm missing
> here. Without ever having used proper coroutines elsewhere, I have no
> real way to appreciate their benefits without a good example.
One example which is commonly given is to implement a web application using
continuations. So in Python terms a session is handled by a generator which
yields a form to be sent back to the user and the user's response is sent
in to the request using the generator's send method. State would be
maintained in the generator. Whether this actually works well in practice
(and how you handle things like a back button on the forms) is another
matter.
So very roughly your web code might look like this:
def checkout(basket):
orderOk = False
while not OrderOk:
order = (yield OrderForm(basket))
address = (yield AddressForm())
payment = (yield PaymentForm(order.total))
confirmation = (yield ConfirmationForm(order, address, payment))
orderOk = confirmation.confirmed
placeOrder(order, address, payment)
yield OrderPlacedPage()
More information about the Python-list
mailing list