Saturday, June 04, 2005

Python: Generator Expressions

In one of his talks at PyCon, Alex Martelli said that if you have complicated loop logic, throw it into a generator so that you never have to duplicate it. In the old days, it was common to duplicate loop logic. I like this rule, and I have seen it improve my code. Just in case you haven't seen the syntax yet, it's:

>>> def generate():
... yield 1
... yield 79
... yield 26
... for i in range(0, 10):
... yield i
...
>>> for i in generate():
... print i,
...
1 79 26 0 1 2 3 4 5 6 7 8 9

In Python 2.4, generator expressions were added. When I saw these, I figured, "Well, yeah, that's pretty natural." It took me a while to realize that just as list comprehensions were taken from Haskell, generator expressions are lazy lists from Haskell. Again, here's an example:

>>> import itertools
>>> import random
>>>
>>> numbers = (random.random() for i in itertools.repeat(0))
>>> print "The sum of 10 random numbers is:", sum(itertools.islice(numbers, 10))
The sum of 10 random numbers is: 4.83875818377

Thursday, June 02, 2005

Python: HTMLTemplate

Paul Abrams suggested to me the idea of having 100% pure HTML, and then using some DOM on the server side to splice chunks of HTML together. After talking about it for about two hours, I became excited about the idea, and I wondered if it would be pleasant in practice in contrast to, say, Cheetah. At the very least, it would be an interesting alternative.

It turns out that HTMLTemplate is one such system. I asked the Python web-sig about it, as well as a few other people. Tung Wai Yip said that he really liked HTMLTemplate. I figured my buddy, Donovan Preston, of Nevow fame would like it because he's a fan of getting away from the whole "big chunk of HTML in an amorphous string" idea. Ian Bicking had the following comment, which I feel was very perceptive:

If there's no code then it's not a presentation layer. It's an HTML layer, nothing more, just dumb data. Presentation requires logic.

Ksenia Marasanova, the newest member added to the Aquarium project, had the following comments based on real experience:

I used it quite a lot, and while it is fast, bugs free and simple to use, total separation of markup and code is IMHO contraproductive - every simple change mostly requires changing two files.

Since Ksenia's opinion is based on experience, it carries a lot of weight in my mind. Feel free to add your comments below.