Skip to content

Commit

Permalink
Add a (somewhat simple-minded) cache to the Python 2 version too. (#291)
Browse files Browse the repository at this point in the history
Fixes #290.
  • Loading branch information
gvanrossum authored Oct 5, 2016
1 parent a5d54a7 commit 2dbf3fd
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions python2/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,29 @@ 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."""

Expand Down Expand Up @@ -686,6 +709,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(
Expand Down Expand Up @@ -731,6 +755,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)]
Expand Down Expand Up @@ -791,6 +816,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,))
Expand Down Expand Up @@ -1109,6 +1135,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,)
Expand Down

0 comments on commit 2dbf3fd

Please sign in to comment.