@@ -142,30 +142,35 @@ def __ne__(self, other):
142142
143143_CacheInfo = namedtuple ("CacheInfo" , ["hits" , "misses" , "maxsize" , "currsize" ])
144144
145- class _CacheKey (list ):
146- 'Make a cache key from optionally typed positional and keyword arguments'
147-
145+ class _HashedSeq (list ):
148146 __slots__ = 'hashvalue'
149147
150- def __init__ (self , args , kwds , typed ,
151- kwd_mark = (object (),),
152- sorted = sorted , tuple = tuple , type = type , hash = hash ):
153- key = args
154- if kwds :
155- sorted_items = sorted (kwds .items ())
156- key += kwd_mark
157- for item in sorted_items :
158- key += item
159- if typed :
160- key += tuple (type (v ) for v in args )
161- if kwds :
162- key += tuple (type (v ) for k , v in sorted_items )
163- self [:] = key
164- self .hashvalue = hash (key ) # so we only have to hash just once
148+ def __init__ (self , tup , hash = hash ):
149+ self [:] = tup
150+ self .hashvalue = hash (tup )
165151
166152 def __hash__ (self ):
167153 return self .hashvalue
168154
155+ def _make_key (args , kwds , typed ,
156+ kwd_mark = (object (),),
157+ fasttypes = {int , str , frozenset , type (None )},
158+ sorted = sorted , tuple = tuple , type = type , len = len ):
159+ 'Make a cache key from optionally typed positional and keyword arguments'
160+ key = args
161+ if kwds :
162+ sorted_items = sorted (kwds .items ())
163+ key += kwd_mark
164+ for item in sorted_items :
165+ key += item
166+ if typed :
167+ key += tuple (type (v ) for v in args )
168+ if kwds :
169+ key += tuple (type (v ) for k , v in sorted_items )
170+ elif len (key ) == 1 and type (key [0 ]) in fasttypes :
171+ return key [0 ]
172+ return _HashedSeq (key )
173+
169174def lru_cache (maxsize = 128 , typed = False ):
170175 """Least-recently-used cache decorator.
171176
@@ -193,7 +198,7 @@ def lru_cache(maxsize=128, typed=False):
193198
194199 # Constants shared by all lru cache instances:
195200 sentinel = object () # unique object used to signal cache misses
196- make_key = _CacheKey # build a key from the function arguments
201+ make_key = _make_key # build a key from the function arguments
197202 PREV , NEXT , KEY , RESULT = 0 , 1 , 2 , 3 # names for the link fields
198203
199204 def decorating_function (user_function ):
0 commit comments