@@ -1495,6 +1495,59 @@ def square(x):
14951495 self .assertEqual (square .cache_info ().hits , 4 )
14961496 self .assertEqual (square .cache_info ().misses , 4 )
14971497
1498+ def test_lru_with_container_types (self ):
1499+ def identity (x ):
1500+ return x
1501+
1502+ values = [(), (1 , 2 ), (1 , 2 , 'a' )]
1503+ for maxsize in (None , 128 ):
1504+ for current_value in values :
1505+ with self .subTest (current_value = current_value , maxsize = maxsize ):
1506+ cached = self .module .lru_cache (maxsize , typed = True )(identity )
1507+
1508+ # some unrelated tuple:
1509+ cached ((1 , 2 , 3 , 4 , 5 )) # miss
1510+ cached ((1 , 2 , 3 , 4 , 5 )) # hit
1511+
1512+ cached (current_value ) # miss
1513+ res = cached (current_value ) # hit
1514+
1515+ self .assertEqual (res , current_value )
1516+ self .assertEqual (cached .cache_info ().hits , 2 )
1517+ self .assertEqual (cached .cache_info ().misses , 2 )
1518+
1519+ def test_lru_with_container_types_hash_collision (self ):
1520+ # https://bugs.python.org/issue45701
1521+ def get_zeroth (x ):
1522+ return x [0 ]
1523+
1524+ values = [
1525+ # All values inside each tuple have the same hash:
1526+ # `hash(1) == hash(1.0) == hash(True)`
1527+ (0 , 0.0 , False ),
1528+ (1 , 1.0 , True ),
1529+ ]
1530+ for maxsize in (None , 128 ):
1531+ for hash_collision in values :
1532+ with self .subTest (maxsize = maxsize , values = values ):
1533+ cached = self .module .lru_cache (
1534+ maxsize ,
1535+ typed = True ,
1536+ )(get_zeroth )
1537+
1538+ # All these calls will be cached, because hash is the same.
1539+ self .assertEqual (type (hash_collision [0 ]), int )
1540+ self .assertEqual ( # miss, cache created
1541+ type (cached ((hash_collision [0 ], 2 ))),
1542+ int ,
1543+ )
1544+
1545+ for value in hash_collision : # 3 hits
1546+ self .assertEqual (type (cached ((value , 2 ))), int )
1547+
1548+ self .assertEqual (cached .cache_info ().hits , 3 )
1549+ self .assertEqual (cached .cache_info ().misses , 1 )
1550+
14981551 def test_lru_with_keyword_args (self ):
14991552 @self .module .lru_cache ()
15001553 def fib (n ):
0 commit comments