Skip to content

Commit

Permalink
bpo-45679: Fix caching of multi-value typing.Literal (GH-29334)
Browse files Browse the repository at this point in the history
Literal[True, 2] is no longer equal to Literal[1, 2].
(cherry picked from commit 634984d)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
  • Loading branch information
miss-islington and serhiy-storchaka committed Oct 31, 2021
1 parent da222b7 commit 3997f3c
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 6 deletions.
4 changes: 4 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,8 @@ def test_equal(self):
self.assertNotEqual(Literal[True], Literal[1])
self.assertNotEqual(Literal[1], Literal[2])
self.assertNotEqual(Literal[1, True], Literal[1])
self.assertNotEqual(Literal[1, True], Literal[1, 1])
self.assertNotEqual(Literal[1, 2], Literal[True, 2])
self.assertEqual(Literal[1], Literal[1])
self.assertEqual(Literal[1, 2], Literal[2, 1])
self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])
Expand Down Expand Up @@ -4917,6 +4919,8 @@ def test_special_attrs(self):
typing.Concatenate[Any, SpecialAttrsP]: 'Concatenate',
typing.Final[Any]: 'Final',
typing.Literal[Any]: 'Literal',
typing.Literal[1, 2]: 'Literal',
typing.Literal[True, 2]: 'Literal',
typing.Optional[Any]: 'Optional',
typing.TypeGuard[Any]: 'TypeGuard',
typing.Union[Any]: 'Any',
Expand Down
11 changes: 5 additions & 6 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,10 @@ def __getitem__(self, parameters):


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


@_SpecialForm
Expand Down Expand Up @@ -528,7 +529,8 @@ def Optional(self, parameters):
return Union[arg, type(None)]

@_LiteralSpecialForm
def Literal(self, parameters):
@_tp_cache(typed=True)
def Literal(self, *parameters):
"""Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
Expand All @@ -551,9 +553,6 @@ def open_helper(file: str, mode: MODE) -> str:
"""
# There is no '_type_check' call because arguments to Literal[...] are
# values, not types.
if not isinstance(parameters, tuple):
parameters = (parameters,)

parameters = _flatten_literal_params(parameters)

try:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix caching of multi-value :data:`typing.Literal`. ``Literal[True, 2]`` is no
longer equal to ``Literal[1, 2]``.

0 comments on commit 3997f3c

Please sign in to comment.