Real-world use cases for map's None fill-in feature?

Duncan Booth duncan.booth at invalid.invalid
Mon Jan 9 03:44:27 EST 2006


Raymond Hettinger wrote:

> My request for readers of comp.lang.python is to search your own code
> to see if map's None fill-in feature was ever used in real-world code
> (not toy examples).  I'm curious about the context, how it was used,
> and what alternatives were rejected (i.e. did the fill-in feature
> improve the code).  Likewise, I'm curious as to whether anyone has seen
> a zip-style fill-in feature employed to good effect in some other
> programming language.

One example of padding out iterators (although I didn't use map's fill-in 
to implement it) is turning a single column of items into a multi-column 
table with the items laid out across the rows first. The last row may have 
to be padded with some empty cells.

Here's some code I wrote to do that. Never mind for the moment that the use 
of zip isn't actually defined here, it could use izip, but notice that the 
input iterator has to be converted to a list first so that I can add a 
suitable number of empty strings to the end. If there was an option to izip 
to pad the last element with a value of choice (such as a blank string) the 
code could work with iterators throughout:

    def renderGroups(self, group_size=2, allow_add=True):
        """Iterates over the items rendering one item for each group.
        Each group contains an iterator for group_size elements.
        The last group may be padded out with empty strings.
        """
        elements = list(self.renderIterator(allow_add)) + ['']*(group_size-
1)
        eliter = iter(elements)
        return zip(*[eliter]*group_size)

If there was a padding option to izip this could could have been something 
like:

    def renderGroups(self, group_size=2, allow_add=True):
        """Iterates over the items rendering one item for each group.
        Each group contains an iterator for group_size elements.
        The last group may be padded out with empty strings.
        """
        iter = self.renderIterator(allow_add)
        return itertools.izip(*[iter]*group_size, pad='')

The code is then used to build a table using tal like this:

    <tal:loop repeat="row python:slot.renderGroups(group_size=4);">
      <tr tal:define="isFirst repeat/row/start"                 
          tal:attributes="class python:test(isFirst, 'slot-top','')">
        <td class="slotElement" tal:repeat="cell row" 
            tal:content="structure cell">4X Slot element</td>
      </tr>
    </tal:loop>



More information about the Python-list mailing list