File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -583,7 +583,19 @@ def update(self, other):
583583 if not other :
584584 return
585585 if isinstance (other , LimitedSet ):
586- self ._data .update (other ._data )
586+ # Give the entries sequence numbers of this set, in the other
587+ # set's order: its own numbers can be the same as ours, and two
588+ # entries with the same insertion time and sequence number make
589+ # the heap compare the items themselves.
590+ entries = sorted (
591+ other ._data .values (),
592+ # insertion time, then the other set's sequence number
593+ key = lambda entry : entry [:2 ],
594+ )
595+ for inserted , other_seq , item in entries :
596+ # other_seq was only needed for the order above: the entry
597+ # gets a sequence number of this set instead.
598+ self ._data [item ] = (inserted , next (self ._seq ), item )
587599 self ._refresh_heap ()
588600 self .purge ()
589601 elif isinstance (other , dict ):
Original file line number Diff line number Diff line change @@ -539,6 +539,44 @@ def test_discard_does_not_expire_next_item(self):
539539 assert len (s ) == 100
540540 assert 0 in s
541541
542+ # Sequence numbers copied by update() from another LimitedSet.
543+ def test_add_after_update_from_limited_set (self ):
544+ other = LimitedSet ()
545+ other .add ('x' , now = 5.0 )
546+ s = LimitedSet ()
547+ s .update (other )
548+ # Same insertion time as the copied entry.
549+ s .add (1 , now = 5.0 )
550+ assert list (s ) == ['x' , 1 ]
551+ assert s .pop () == 'x'
552+ assert s .pop () == 1
553+
554+ def test_update_from_limited_set_into_non_empty_set (self ):
555+ other = LimitedSet ()
556+ other .add ('x' , now = 5.0 )
557+ s = LimitedSet ()
558+ s .add (1 , now = 5.0 )
559+ s .update (other )
560+ assert list (s ) == [1 , 'x' ]
561+
562+ def test_init_from_limited_set (self ):
563+ other = LimitedSet ()
564+ other .add ('x' , now = 5.0 )
565+ s = LimitedSet (data = other )
566+ s .add (1 , now = 5.0 )
567+ assert list (s ) == ['x' , 1 ]
568+
569+ def test_update_from_limited_set_keeps_its_order (self ):
570+ other = LimitedSet ()
571+ for i in range (3 ):
572+ other .add (f'item{ i } ' , now = 1.0 )
573+ s = LimitedSet (maxlen = 2 )
574+ s .update (other )
575+ # Same insertion time: the item added first there is the oldest.
576+ assert list (s ) == ['item1' , 'item2' ]
577+ assert len (s ._heap ) == len (s )
578+ assert other .as_dict () == {f'item{ i } ' : 1.0 for i in range (3 )}
579+
542580
543581class test_AttributeDict :
544582
You can’t perform that action at this time.
0 commit comments