set.add() doesn't replace equal element

Paul Bryan pbryan at anode.ca
Fri Dec 30 18:00:15 EST 2022


It seems to me like you have to ideas of what "equal" means. You want 
to update a "non-equal/equal" value in the set (because of a different 
time stamp). If you truly considered them equal, the time stamp would 
be irrelevant and updating the value in the set would be unnecessary.

I would:

a) /not/ consider two different leases with two different time stamps 
to be equal, and
b) as already mentioned, store them in another data structure like a 
dictionary.

Not knowing the specifics of the DHCP object structure, if a DHCP lease 
object has some immutable key or other durable immutable attribute, I 
would be inclined to make that the dictionary key, and store the DHCP 
object as the value.


On Fri, Dec 30 2022 at 04:27:56 PM -0600, Ian Pilcher 
<arequipeno at gmail.com> wrote:
> 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