[Tutor] help with refactoring needed -- which approach is more Pythonic?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Feb 10 01:06:25 CET 2005


> If we want to be fancy, we can also take advantage of Python's generator
> support to avoid constructing an explicit list:
>
> ###
>     def partition_node_content(self, body_contents):
>         """Returns an iterator whose contents are a bunch of
>            node_content lists."""
>         current_node_contents = []
>         for line in body_contents:
>             if line == node_end_tag:
>                 yield current_node_contents
>                 current_node_contents = []
> ###


Hi Brian,


Oh good grief.  *grin*

That last snippet won't work; I had forgotten about appending lines into
current_node_contents.  Here's a revision of the silly code:


###
    def partition_node_content(self, body_contents):
        """Returns an iterator whose contents are a bunch of
           node_content lists."""
        current_node_contents = []
        for line in body_contents:
            current_node_contents.append(line)
            if line == node_end_tag:
                yield current_node_contents
                current_node_contents = []
###


I wanted to add that the generator approach should have the same
performance characteristic as your original code.

Your original code's approach interleaved the bundling of the body_content
with calls to the node parser.  The approach with the separate list
bundling behaves a little bit differently: it tries to build a list of all
the node_content chunks, and then processes that list element by element.
The generator approach, like your original code, interleaves the bundling
with the node_content parsing.


My apologies!



More information about the Tutor mailing list