@@ -270,6 +270,7 @@ def __gt__(self, other):
270270lst .sort (key = C )
271271assert lst == [1 , 2 , 3 , 4 , 5 ]
272272
273+
273274# Test that sorted() uses __lt__ (not __gt__) for comparisons.
274275# Track which comparison method is actually called during sort.
275276class TrackComparison :
@@ -287,29 +288,36 @@ def __gt__(self, other):
287288 TrackComparison .gt_calls += 1
288289 return self .value > other .value
289290
291+
290292# Reset and test sorted()
291293TrackComparison .lt_calls = 0
292294TrackComparison .gt_calls = 0
293295items = [TrackComparison (3 ), TrackComparison (1 ), TrackComparison (2 )]
294296sorted (items )
295297assert TrackComparison .lt_calls > 0 , "sorted() should call __lt__"
296- assert TrackComparison .gt_calls == 0 , f"sorted() should not call __gt__, but it was called { TrackComparison .gt_calls } times"
298+ assert TrackComparison .gt_calls == 0 , (
299+ f"sorted() should not call __gt__, but it was called { TrackComparison .gt_calls } times"
300+ )
297301
298302# Reset and test list.sort()
299303TrackComparison .lt_calls = 0
300304TrackComparison .gt_calls = 0
301305items = [TrackComparison (3 ), TrackComparison (1 ), TrackComparison (2 )]
302306items .sort ()
303307assert TrackComparison .lt_calls > 0 , "list.sort() should call __lt__"
304- assert TrackComparison .gt_calls == 0 , f"list.sort() should not call __gt__, but it was called { TrackComparison .gt_calls } times"
308+ assert TrackComparison .gt_calls == 0 , (
309+ f"list.sort() should not call __gt__, but it was called { TrackComparison .gt_calls } times"
310+ )
305311
306312# Reset and test sorted(reverse=True) - should still use __lt__, not __gt__
307313TrackComparison .lt_calls = 0
308314TrackComparison .gt_calls = 0
309315items = [TrackComparison (3 ), TrackComparison (1 ), TrackComparison (2 )]
310316sorted (items , reverse = True )
311317assert TrackComparison .lt_calls > 0 , "sorted(reverse=True) should call __lt__"
312- assert TrackComparison .gt_calls == 0 , f"sorted(reverse=True) should not call __gt__, but it was called { TrackComparison .gt_calls } times"
318+ assert TrackComparison .gt_calls == 0 , (
319+ f"sorted(reverse=True) should not call __gt__, but it was called { TrackComparison .gt_calls } times"
320+ )
313321
314322lst = [5 , 1 , 2 , 3 , 4 ]
315323
0 commit comments