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

Brian van den Broek bvande at po-box.mcgill.ca
Thu Feb 10 01:52:18 CET 2005


Danny Yoo said unto the world upon 2005-02-09 19:06:
>>If we want to be fancy, we can also take advantage of Python's generator
>>support to avoid constructing an explicit list:
>>
<SNIP code like that below but missing the .append()>
> 
> 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!

Hi Danny,

Apologies, while nice, aren't needed; catching your small thinko was 
the easy part of the generator code. :-) (Of the parts of Python about 
which I am still fuzzy, generators are among the fuzziest.) And thank 
you for the replies.

Given that in my application, neither performance nor memory use 
matter too much, are there are grounds (beyond bare personal 
preference) to choose amongst the approaches? (Having rejected 
personal preference and performance as criterion, one might well 
wonder what's left? I mean something like community consensus about 
which is more elegant, etc. where there is enough agreement to take it 
out of the realm of pure personal preference. And, seeing how I've 
phrased it, I think `that's unanswerable' might well be a perfectly 
acceptable answer. :-) )

Alternatively, of the two ways you gave (the generator above and the 
helper function route), which seems better? All I have to guide me is 
unfamiliarity with generators, and that isn't the best compass.

Thanks again,

Brian vdB


More information about the Tutor mailing list