Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 18 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3298,6 +3298,24 @@ def test_top_level_class_var(self):
):
get_type_hints(ann_module6)

def test_hints_with_literal_cache(self):
# https://bugs.python.org/issue45679
Literal[True] # to trigger cache
def func(arg: Literal[1]):
pass

hints = get_type_hints(func)
# We use such complex way of comparing things, because `1 == True`
self.assertEqual(str(hints['arg']), "typing.Literal[1]")

# Two args case, which was causing an issue:
Literal[1, 'a']
def func(arg: Literal[True, 'a']):
pass

hints = get_type_hints(func)
self.assertEqual(str(hints['arg']), "typing.Literal[True, 'a']")


class GetUtilitiesTestCase(TestCase):
def test_get_origin(self):
Expand Down
12 changes: 8 additions & 4 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,10 +312,14 @@ def decorator(func):

@functools.wraps(func)
def inner(*args, **kwds):
try:
return cached(*args, **kwds)
except TypeError:
pass # All real errors (not unhashable args) are raised below.
# We call `cached`, only if we don't care about types,
# or when we have just a single argument. Otherwise we can confuse
# `Literal[1, 'a']` with `Literal[True, 'a']`, see: bpo-45679
if not typed or len(args) <= 1:
try:
return cached(*args, **kwds)
except TypeError:
pass # All real errors (not unhashable args) are raised below.
return func(*args, **kwds)
return inner

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Do not cache :class:`typing.Literal` when it has more than one type
argument.