agronholm / typeguard

Run-time type checker for Python
Other
1.52k stars 114 forks source link

Using NotRequired disables Literal typechecks #454

Open ionelmc opened 6 months ago

ionelmc commented 6 months ago

Things to check first

Typeguard version

4.2.1

Python version

3.11.8

What happened?

Python 3.11.8 (main, Feb 28 2024, 00:00:00) [GCC 13.2.1 20231011 (Red Hat 13.2.1-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import typing
>>> class StuffOptional(typing.TypedDict):
...   foo: typing.NotRequired[typing.Literal['bar']]
...
>>> check_type({'foo': 'caca'}, StuffOptional)
{'foo': 'caca'}
>>>

The expected result would be exactly like this:

>>> class Stuff(typing.TypedDict):
...   foo: typing.Literal['bar']
...
>>> from typeguard import check_type
>>> check_type({'foo': 'caca'}, Stuff)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".tox/py311/lib/python3.11/site-packages/typeguard/_functions.py", line 106, in check_type
    check_type_internal(value, expected_type, memo)
  File ".tox/py311/lib/python3.11/site-packages/typeguard/_checkers.py", line 779, in check_type_internal
    checker(value, origin_type, args, memo)
  File ".tox/py311/lib/python3.11/site-packages/typeguard/_checkers.py", line 284, in check_typed_dict
    check_type_internal(argvalue, argtype, memo)
  File ".tox/py311/lib/python3.11/site-packages/typeguard/_checkers.py", line 779, in check_type_internal
    checker(value, origin_type, args, memo)
  File ".tox/py311/lib/python3.11/site-packages/typeguard/_checkers.py", line 587, in check_literal
    raise TypeCheckError(f"is not any of ({formatted_args})") from None
typeguard.TypeCheckError: value of key 'foo' of dict is not any of ('bar')

How can we reproduce the bug?

^