Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Use typed lru_cache for Literal type
  • Loading branch information
uriyyo committed Nov 15, 2020
commit b8a597a7279d54957158473fa5efa4d81884c586
3 changes: 3 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,9 @@ def test_no_multiple_subscripts(self):
Literal[1][1]

def test_equal(self):
self.assertNotEqual(Literal[0], Literal[False])
self.assertNotEqual(Literal[True], Literal[1])
self.assertNotEqual(Literal[1], Literal[2])
self.assertNotEqual(Literal[1, True], Literal[1])
Comment thread
uriyyo marked this conversation as resolved.
Outdated
self.assertEqual(Literal[1], Literal[1])
self.assertEqual(Literal[1, 2], Literal[2, 1])
Expand Down
36 changes: 24 additions & 12 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,22 +242,27 @@ def _flatten_literal_params(parameters):
_cleanups = []


def _tp_cache(func):
def _tp_cache(typed=False):
"""Internal wrapper caching __getitem__ of generic types with a fallback to
original function for non-hashable arguments.
Comment thread
uriyyo marked this conversation as resolved.
"""
cached = functools.lru_cache()(func)
_cleanups.append(cached.cache_clear)
if callable(typed):
return _tp_cache()(typed)

@functools.wraps(func)
def inner(*args, **kwds):
try:
return cached(*args, **kwds)
except TypeError:
pass # All real errors (not unhashable args) are raised below.
return func(*args, **kwds)
return inner
def decorator(func):
cached = functools.lru_cache(typed=typed)(func)
_cleanups.append(cached.cache_clear)

@functools.wraps(func)
def inner(*args, **kwds):
try:
return cached(*args, **kwds)
except TypeError:
pass # All real errors (not unhashable args) are raised below.
return func(*args, **kwds)
return inner

return decorator

def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
"""Evaluate all forward references in the given type t.
Expand Down Expand Up @@ -330,6 +335,13 @@ def __subclasscheck__(self, cls):
def __getitem__(self, parameters):
return self._getitem(self, parameters)


class _LiteralSpecialForm(_SpecialForm, _root=True):
@_tp_cache(typed=True)
def __getitem__(self, parameters):
return self._getitem(self, parameters)


@_SpecialForm
def Any(self, parameters):
"""Special type indicating an unconstrained type.
Expand Down Expand Up @@ -447,7 +459,7 @@ def Optional(self, parameters):
arg = _type_check(parameters, f"{self} requires a single type.")
return Union[arg, type(None)]

@_SpecialForm
@_LiteralSpecialForm
def Literal(self, parameters):
"""Special typing form to define literal types (a.k.a. value types).

Expand Down