Augmented assignment again

Huaiyu Zhu hzhu at localhost.localdomain
Wed Aug 30 12:39:26 EDT 2000


On Wed, 30 Aug 2000 08:28:58 +0200, Rpoeland Rengelink
<r.b.rigilink at cable.a2000.nl> wrote: 

>Since I expect the following to be(come) a common problem with the
>introduction of augmented assignment in Python, I thought I'd put this
>up for review
[snip]

>>>> d = a+b+c
[snip]
>while we would like this to be equivalent to.
>
>>>> tmp = a.copy()
>>>> tmp += b
>>>> tmp += c
>>>> d = tmp

As Thomas pointed out, an object does not know when it is assigned to
another name or other holding place.  So it seems the programmer has to tell
when an object is temporary or fixed.

Here's an adaptation of your second method.  Any better ideas?  


"""
Use temporary objects with augmented assignments
Warning: objects not fixed are subject to change!
"""

class Obj:
    def __init__(self, data):
        self.data = data
        self.is_temporary = 0

    def __add__(self, other):
        if self.is_temporary:
            self += other
            return self
        else:
            result = self.copy()
            result.is_temporary = 1
            result += other
            return result

    def __add_ab__(self, other):
        self.data += other.data
        return self

    def copy(self):
        print "Copying ..."
        return Obj(self.data)

    def fix(self):
        self.is_temporary = 0
        return self

if __name__ == "__main__":
    a = Obj(2)
    b = Obj(3)

    print "This makes only one copy"
    c = a+b+a
    print "This does not make extra copy"
    d = c+b
    print "This makes one extra copy"
    c = (a+b+c).fix()
    e = c+c 

The result is

This makes only one copy
Copying ...
This does not make extra copy
This makes one extra copy
Copying ...
Copying ...


Huaiyu

-- 
Huaiyu Zhu                       hzhu at users.sourceforge.net
Matrix for Python Project        http://MatPy.sourceforge.net 



More information about the Python-list mailing list