FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Add a (somewhat simple-minded) cache to the Python 2 version too. by gvanrossum · Pull Request #291 · python/typing · GitHub

Repository navigation

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (1) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
27 changes: 27 additions & 0 deletions python2/typing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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

Back | FazBrowse Home | New Git URL