Can someone help me with this bug?

Dan Bishop danb_83 at yahoo.com
Thu May 27 21:26:23 EDT 2004


"Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in message news:<c95724$8fu$1 at news8.svr.pol.co.uk>...
> Hello,
>          I'm probably missing something that should be obvious, but can
> anyone tell me what's wrong with the following?
> 
> temp.py
> ---------------------------------------------------------------------
> 
> class Item(object):
>     def __init__(self, id, data):
>         self.id = id
>         self.data = data
>
> class KeyedSet(dict):
>     def __init__(self, items=None):
>         if items is not None:
>             for item in items:
>                 self[item.id] = item
>     def __iter__(self):
>         return self.itervalues()
>     def __repr__(self):
>         return '%s(%r)' % (self.__class__.__name__, self.keys())
>     def __contains__(self, item):
>         return self.has_key(item.id)
>     def intersection(self, other):
>         res = self.__class__()
>         for item in self:
>             if item in other:
>                 res[item.id] = item
>         return res
>     def __and__(self, other):
>         return self.intersection(other)
>     def intersection_update(self, other):
>         self &= other
>     def __iand__(self, other):
>         self = self.intersection(other)
>         return self
> --------------------------------------------------------------------
> 
> >>> from temp import Item, KeyedSet
> >>> a = Item(0, 'W')
> >>> b = Item(1, 'X')
> >>> c = Item(2, 'Y')
> >>> d = Item(3, 'Z')
> >>> aset = KeyedSet([a, b, c])
> >>> bset = KeyedSet([b, c, d])
> >>> aset &= bset
> >>> aset
>  KeyedSet([1, 2])
> >>> aset = KeyedSet([a, b, c])
> >>> aset.intersection_update(bset)
> >>> aset
>  KeyedSet([0, 1, 2])
> >>>
> 
> I can't figure out why 'aset' is unchanged?  Thanks.

Your __iand__ method doesn't work the way that you think it does. 
Remember, "self" is just another local variable name, so your function
works as if you had done:

     def __iand__(self, other):
         x = self.intersection(other)
         return x

which (incorrectly) has the same effect as __and__.



More information about the Python-list mailing list