wow! (generators) - suggestion (yield saved)

Ken Seehof kseehof at neuralintegrator.com
Sun Aug 5 07:52:00 EDT 2001


From: "Roman Suzi" <rnd at onego.ru>
>
> Hello!
>
> The following code is from CGI script and provides way to have
> nice calendar:
>
> ------------------------------------------------------------
> from __future__ import generators
> import calendar, string
> def calt(year, month):
>     month_cal = calendar.monthcalendar(year, month)
>     yield """<B>%s.%s</B>""" % (month, year)
>     yield """<TABLE BORDER=1>"""
>     for week in month_cal:
>       yield """\n<TR>"""
>       for day in week:
>         yield """<TD>%s</TD>""" % (day or " ")
>       yield """</TR>"""
>     yield """</TABLE>"""
>
> print string.join(calt(2001, 8), "")
> --------------------------------------------------------
>
> I like generators :-)
> (Probably Python should use "black bullet" or "*" instead of "yield":
>
> --------------------------------------------------------
> from __future__ import generators
> import calendar, string
> def calt(year, month):
>     month_cal = calendar.monthcalendar(year, month)
>     * """<B>%s.%s</B>""" % (month, year)
>     * """<TABLE BORDER=1>"""
>     for week in month_cal:
>       * """\n<TR>"""
>       for day in week:
>         * """<TD>%s</TD>""" % (day or " ")
>       * """</TR>"""
>     * """</TABLE>"""
>
> print string.join(calt(2001, 8), "")
> ----------------------------------------------------------------
>
> What do you think?
>
> Sincerely yours, Roman Suzi

This is python, not perl.  Readability therefore has priority over terse
obfuscation.  I definitely prefer 'yield' over '*'.

The only argument I can think of in favor of '*' is that it avoids
introducing
a keyword, and therefore is more backward compatible.  Since I don't
think I have any legacy code with 'yield' in it (knocking on wood), I will
gladly accept a new keyword to avoid perlization of the python language.

While your use of generators is clever, I'm not sure what, if anything
generators are actually buying you here.

What's wrong with:

import calendar, string
def calt(year, month):
    month_cal = calendar.monthcalendar(year, month)
    scal = ''
    scal += "<B>%s.%s</B>" % (month, year)
    scal += "<TABLE BORDER=1>"
    for week in month_cal:
      scal += "\n<TR>"
      for day in week:
        scal += "<TD>%s</TD>" % (day or " ")
      scal += "</TR>"
    scal += "</TABLE>"
    return scal

Unless, of course you are trying to sell python to a sceptical client
who, you happen to know, loves generators. :-)

BTW, nice calendar format.

- Ken Seehof
kseehof at neuralintegrator.com
www.neuralintegrator.com/kseehof







More information about the Python-list mailing list