set.add() doesn't replace equal element

Ian Pilcher arequipeno at gmail.com
Fri Dec 30 17:27:56 EST 2022


On 12/30/22 15:47, Paul Bryan wrote:
> What kind of elements are being added to the set? Can you show 
> reproducible sample code?

The objects in question are DHCP leases.  I consider them "equal" if
the lease address (or IPv6 prefix) is equal, even if the timestamps have
changed.  That code is not small, but it's easy to demonstrate the
behavior.

 >>> import datetime
 >>> class Foo(object):
...     def __init__(self, index):
...         self.index = index
...         self.timestamp = datetime.datetime.now()
...     def __eq__(self, other):
...         return type(other) is Foo and other.index == self.index
...     def __hash__(self):
...         return hash(self.index)
...     def __repr__(self):
...         return f'Foo({self.index}) created at {str(self.timestamp)}'
...
 >>> f1 = Foo(1)
 >>> s = { f1 }
 >>> s
{Foo(1) created at 2022-12-30 16:24:12.352908}
 >>> f2 = Foo(1)
 >>> f2
Foo(1) created at 2022-12-30 16:24:35.489208
 >>> s.add(f2)
 >>> s
{Foo(1) created at 2022-12-30 16:24:12.352908}

-- 
========================================================================
Google                                      Where SkyNet meets Idiocracy
========================================================================



More information about the Python-list mailing list