@@ -121,12 +121,16 @@ def __ne__(self, other):
121121
122122_CacheInfo = namedtuple ("CacheInfo" , "hits misses maxsize currsize" )
123123
124- def lru_cache (maxsize = 100 ):
124+ def lru_cache (maxsize = 100 , typed = False ):
125125 """Least-recently-used cache decorator.
126126
127127 If *maxsize* is set to None, the LRU features are disabled and the cache
128128 can grow without bound.
129129
130+ If *typed* is True, arguments of different types will be cached separately.
131+ For example, f(3.0) and f(3) will be treated as distinct calls with
132+ distinct results.
133+
130134 Arguments to the cached function must be hashable.
131135
132136 View the cache statistics named tuple (hits, misses, maxsize, currsize) with
@@ -142,7 +146,7 @@ def lru_cache(maxsize=100):
142146 # to allow the implementation to change (including a possible C version).
143147
144148 def decorating_function (user_function ,
145- tuple = tuple , sorted = sorted , len = len , KeyError = KeyError ):
149+ * , tuple = tuple , sorted = sorted , map = map , len = len , type = type , KeyError = KeyError ):
146150
147151 hits = misses = 0
148152 kwd_mark = (object (),) # separates positional and keyword args
@@ -156,7 +160,12 @@ def wrapper(*args, **kwds):
156160 nonlocal hits , misses
157161 key = args
158162 if kwds :
159- key += kwd_mark + tuple (sorted (kwds .items ()))
163+ sorted_items = tuple (sorted (kwds .items ()))
164+ key += kwd_mark + sorted_items
165+ if typed :
166+ key += tuple (map (type , args ))
167+ if kwds :
168+ key += tuple (type (v ) for k , v in sorted_items )
160169 try :
161170 result = cache [key ]
162171 hits += 1
@@ -177,7 +186,12 @@ def wrapper(*args, **kwds):
177186 nonlocal hits , misses
178187 key = args
179188 if kwds :
180- key += kwd_mark + tuple (sorted (kwds .items ()))
189+ sorted_items = tuple (sorted (kwds .items ()))
190+ key += kwd_mark + sorted_items
191+ if typed :
192+ key += tuple (map (type , args ))
193+ if kwds :
194+ key += tuple (type (v ) for k , v in sorted_items )
181195 with lock :
182196 try :
183197 result = cache [key ]
0 commit comments