Augmented Assignment question
Adam Ruth
owski at hotmail.com
Wed Jul 16 15:25:01 EDT 2003
In <215bhv0bnkn13eivh0s64ic5ml8obpgfg7 at 4ax.com> Doug Tolton wrote:
> I have a function that returns a tuple:
>
> def checkdoc(self, document):
> blen = document['length']
> bates = document['obates']
>
> normal, truncated, semicolon = 0,0,0
> for bat in bates:
> if len(bat) == 2 * blen:
> semicolon += 1
> if len(bat) == blen - 1:
> truncated += 1
> if len(bat) == blen:
> normal += 1
>
> return normal, truncated, semicolon
>
> on the other side I have 3 variables:
> normal, truncated and semicolon
>
> I would like to be able to do an augmented assignment such as:
>
> normal, truncated, semicol += self.checkdoc(mydoc)
>
> however this returns the following error:
> SyntaxError: augmented assign to tuple not possible
>
> I did some reading and it seems that an augmented assignment is
> specifically verboten on tuples and lists. Is there a clean way to
> accomplish this? I dislike in the extreme what I've resorted to:
>
> 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?
>
> Thanks in advance,
> Doug Tolton
> dougt at<remove this>case<remove this too>data dot com
>
I don't think it's all that inelegant, and it's definitely clear. I can
see, though, why a one liner would seem a little cleaner.
Off the top of my head, I'd say to change your checkdoc function to this:
> def checkdoc(self, document, normal=0, truncated=0, semicolon=0):
> blen = document['length']
> bates = document['obates']
> for bat in bates:
> if len(bat) == 2 * blen:
> semicolon += 1
> if len(bat) == blen - 1:
> truncated += 1
> if len(bat) == blen:
> normal += 1
>
> return normal, truncated, semicolon
And then call it like this:
> normal, truncated, semicolon = self.checkdoc(curdoc, normal,
> truncated, semicolon)
As a side note, I wouldn't have thought that the augmented assign would
work the way you tried to use it. I would have thought that it would be
analagous to the + operator and sequences:
> x = [1,2,3]
> y = [1,2,3]
> x + y
[1,2,3,1,2,3]
So that the agumented form would be:
> x = [1,2,3]
> x += [1,2,3]
[1,2,3,1,2,3]
But I've never tried it before and didn't know that it didn't work with
sequences. You learn something new every day.
Adam Ruth
More information about the Python-list
mailing list