[issue45679] typing.Literal[True] is implicitly converted to typing.Literal[1]
Van Burgerberg
report at bugs.python.org
Sat Oct 30 11:33:26 EDT 2021
New submission from Van Burgerberg <vanburgerberg at yandex.ru>:
When you create `Literal[1]` annotation and then create `Literal[True]` annotation, in the second case you will actually get `Literal[1]` instead. This is happening because `typing` performs caching of the outcome of parameterizing generics and `hash(True)` is equal to `hash(1)`. I think this behavior is incorrect and may lead to unexpected results.
Why is this inaccuracy important?
Consider the following example:
```python
from typing import Literal
SomeUsefulAlias = Literal[1, "abc"]
def func(arg: Literal[True, "abc"]):
if arg is not True:
arg.capitalize()
```
If we look at `func.__annotations__["arg"]`, we will see `Literal[1, 'abc']`. According to the new annotation, we can pass the value `1` to `func`, and this will lead to an attribute error, as you've already understood. Thus, proper runtime type checking cannot be performed.
----------
components: Library (Lib)
messages: 405371
nosy: vanburgerberg
priority: normal
severity: normal
status: open
title: typing.Literal[True] is implicitly converted to typing.Literal[1]
type: behavior
versions: Python 3.10, Python 3.8, Python 3.9
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45679>
_______________________________________
More information about the Python-bugs-list
mailing list