Augmented Assignment question

Steven Taschuk staschuk at telusplanet.net
Wed Jul 16 22:01:40 EDT 2003


Quoth Doug Tolton:
  [...]
> fnormal, ftruncated, fsemicolon = 0,0,0
> 
> // loop through a file and process all documents:
> 	normal, truncated, semicolon = self.checkdoc(curdoc)
> 	fnormal += normal
> 	ftruncated += truncated
> 	fsemicolon += semicolon
> 
> This solution strikes me as inelegant and ugly.  Is there a cleaner
> way of accomplishing this?

It seems possible that your normal, truncated and semicolon
variables should be bundled into a single object:

    class DocumentStatistics(object):
        # ...
        def __iadd__(self, (deltanormal, deltatruncated, deltasemicolon)):
            self.normal += deltanormal
            self.truncated += deltatruncated
            self.semicolon += deltasemicolon

Then you can just do
    docstats = DocumentStatistics()
    # ...
    docstats += self.checkdoc(curdoc)
If these variables usually change in synch, this seems a natural
way to organize them.

You might also want to look into Numeric's arrays.

(And there's always

    normal, truncated, semicolon = map(operator.add,
                                       (normal, truncated, semicolon),
                                       self.checkdoc(curdoc))

which I consider inferior to your straightforward approach with
three augmented assignments.)

-- 
Steven Taschuk     staschuk at telusplanet.net
"Please don't damage the horticulturalist."
         -- _Little Shop of Horrors_ (1960)





More information about the Python-list mailing list