From 974a0d47550cb0a96f1b98daba39868b03a15bc3 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Tue, 4 Oct 2016 16:42:58 -0700 Subject: [PATCH 1/2] Add a (somewhat simple-minded) cache to the Python 2 version too. --- python2/typing.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/python2/typing.py b/python2/typing.py index f6a73d706..8a1d18ee4 100644 --- a/python2/typing.py +++ b/python2/typing.py @@ -563,6 +563,28 @@ def __subclasscheck__(self, cls): AnyStr = TypeVar('AnyStr', bytes, unicode) +def _tp_cache(func, maxsize=128): + cache = {} + + @functools.wraps(func) + def inner(*args): + key = args + try: + return cache[key] + except TypeError: + # Assume it's an unhashable argument. + return func(*args) + except KeyError: + value = func(*args) + if len(cache) >= maxsize: + # If the cache grows too much, just start over. + cache.clear() + cache[key] = value + return value + + return inner + + class UnionMeta(TypingMeta): """Metaclass for Union.""" @@ -686,6 +708,7 @@ def __repr__(self): for t in self.__union_params__)) return r + @_tp_cache def __getitem__(self, parameters): if self.__union_params__ is not None: raise TypeError( @@ -731,6 +754,7 @@ class _Optional(_FinalTypingBase): __metaclass__ = OptionalMeta __slots__ = () + @_tp_cache def __getitem__(self, arg): arg = _type_check(arg, "Optional[t] requires a single type.") return Union[arg, type(None)] @@ -791,6 +815,7 @@ def __repr__(self): ', '.join(params)) return r + @_tp_cache def __getitem__(self, parameters): if self.__tuple_params__ is not None: raise TypeError("Cannot re-parameterize %r" % (self,)) @@ -1109,6 +1134,7 @@ def __eq__(self, other): def __hash__(self): return hash((self.__name__, self.__parameters__)) + @_tp_cache def __getitem__(self, params): if not isinstance(params, tuple): params = (params,) From 658671e7801aae365c5491a47c318340de021391 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Wed, 5 Oct 2016 08:16:34 -0700 Subject: [PATCH 2/2] Make maxsize a local (it's useless as an arg anyway) --- python2/typing.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python2/typing.py b/python2/typing.py index 8a1d18ee4..6cd51c6b7 100644 --- a/python2/typing.py +++ b/python2/typing.py @@ -563,7 +563,8 @@ def __subclasscheck__(self, cls): AnyStr = TypeVar('AnyStr', bytes, unicode) -def _tp_cache(func, maxsize=128): +def _tp_cache(func): + maxsize = 128 cache = {} @functools.wraps(func)