Using Python Coroutines for AJAX Applications


I think I just had an epiphany regarding the upcoming coroutine support in Python. I don't mean I came up with anything new (I think Ruby programmers have been doing it for a long time), just that I finally grok it—or at least, I think I do.

You see, I'm writing a little AJAX-based flash card website and I started off writing a standalone dynamic HTML mock-up of (obviously) the client side but without any communication to the server yet.

I then wrote a console-based flash card program to experiment with the algorithm I want to use for what card to show when, when to learn new cards, etc. The console-based program just has a function called test that takes a card object, tests the card on the user and returns a boolean as to whether the user got the card right or not.

So my code has a bunch of places where I say:

for card in to_test: correct = test(card) if correct: ... else: ...

In theory, it's only this test function that's throw away. It would be nice if I just had to replace those calls to test when I come to write the server version.

The only catch is that it will be the client that initiates requests for cards. Easy, I thought: I can use yield statements in the server code wherever I want to present the user with the next card. That way, the client (or more accurately some proxy for the client running on the server) can do a next() to get the next card.

The problem is that the client needs to return the result. The yield can't be a one-way street. At the point the server yields a card, it needs to also find out the result of that yield.

Enter coroutines. If I understand correctly, this is exactly the kind of problem coroutines solve. The yield statement in my server-side code becomes a yield expression. The client sends the generator the result of testing the card and that becomes what the yield expression evaluates to.

Have I understood coroutines correctly? If so, I can't wait for Python 2.5!

The original post was in the category: python but I'm still in the process of migrating categories over.

The original post had 8 comments I'm in the process of migrating over.