Inference for Literal arguments not handled
Open
Nobody has claimed this yet.
bug
topic-literal-types
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
If you have a function with Literal arguments, and a variable that is set to one of the options, an error is reported.
To Reproduce
from typing import Literal
def myfun(a: Literal["a", "b", "c"]) -> str:
return a
s = "a"
myfun(s)
def myfun2(a: Literal[1, 2]) -> int:
return a
b = 2
myfun2(b)
c = 1 if s == "a" else 2
myfun2(c)
reports
literalinf.py:10: error: Argument 1 to "myfun" has incompatible type "str"; expected "Union[Literal['a'], Literal['b'], Literal['c']]"
literalinf.py:18: error: Argument 1 to "myfun2" has incompatible type "int"; expected "Union[Literal[1], Literal[2]]"
literalinf.py:21: error: Argument 1 to "myfun2" has incompatible type "int"; expected "Union[Literal[1], Literal[2]]"
Expected Behavior
No error. The values can be inferred to be of the Literal value
Actual Behavior
See above.
Your Environment
- Mypy version used: 0.910
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.8.5
- Operating system and version: Windows 10 21H1
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied Python reproducer with mypy and trace how assigned values and conditional expressions are inferred when checking Literal arguments. Add coverage for the three calls, with the work complete when they no longer produce the reported incompatible-type errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100