[Zope3-dev] Number of languages in Zope 3

Guido van Rossum guido@python.org
Sat, 12 Apr 2003 09:20:38 -0400


[Steve Alexander]
> A generator would fix this.

I've lost some context here, so maybe this is inappropriate.

When I proposed this to Jim in another place where there was a browser
method returning a list for use in a template, we ended up not liking
the generator because it meant you couldn't save it in a variable and
do different code depending on whether it is empty or not.

We also observed that since such lists are usually intended to be
displayed, they are not usually long enough for the space savings of a
generator to be worth it.

This particular example can be rewritten as a list comprehension:

  def getSnippetInfo(self):
      return [{'title': snippet.headline(version='Brief'),
               'tease': snippet.teaseText(maxWords=100)}
               for snippet in self.context.values()
               if ISnippet.isImplementedBy(x)]

which also avoids the dual looping thwt Chris asks about.

> Chris Withers wrote:
> > Hi Tres,
> > 
> > In your example below, what are the preformance implications of 
> > iterating over the result list twice as opposed to just once?
> > 
> > cheers,
> > 
> > Chris
> > 
> > Tres Seaver wrote:
> > 
> >> In Zope3, that idiom would typically be replaced by an intermediate
> >> method on the view class which did the underlying work.  E.g., where in
> >> Zope2 I might to something like:
> >>
> >>   <div tal:repeat="snippet python:here.objectValues(['Some Type'])">
> >>    <h3 tal:conetnt="python:snippet.headline(version='Brief')">HEADLINE
> >>    >/h3>
> >>    <div tal:content="python:snippet.teaseText(maxwords=100)>TEASE</div>
> >>   </div>
> >>
> >> in Zope3 I would add a method to the view class which did the heavy
> >> lifting:
> >>
> >>    def getSnippetInfo(self):
> >>        results = []
> >>        for snippet in [x for x in self.context.values()
> >>                          if ISnippet.isImplementedBy(x) ]:
> >>            results.append({'title' : snppet.headline(version='Brief'),
> >>                            'tease' : snippet.teaseText(maxWords=100)})
> >>        return results
> >>
> >> The template then becomes much clearer:
> >>
> >>    <div tal:repeat="info context/getSnippetInfo">
> >>     <h3 tal:content="info/title">TITLE</h3>
> >>     <div tal:content="info/tease">TEASE</div>
> >>    </div>

--Guido van Rossum (home page: http://www.python.org/~guido/)