Type detection broken on attribute override and not-equal-assertion
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I commonly find myself writing simplified list init parameters. So, if the user provides only a type X, I automatically convert that to list type [X]. In doing so, I found two issue that prevent a proper type detection. See the example code below.
To Reproduce
#!/usr/bin/env python3
from typing import Union, List, Optional
def test(a: Union[List[str], str, None] = None) -> Optional[List[str]]:
if type(a) == str:
a = [a]
assert(type(a) != str)
return a
Expected Behavior
- First, the
type(a) == strcheck and consequent list assignment should remove the str type from the Union choices. - Second, the
assert(!=)check should also remove the str type from the Union options.
Actual Behavior
Both checks do not work and the type is still guessed incorrectly:

Your Environment
- Mypy version used: 0.910
- Mypy command-line flags: pip install
- Mypy configuration options from
mypy.ini(and other config files): - - Python version used: 3.8
- Operating system and version: macOS 10.15
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 provided Python reproducer against mypy and inspect the type-narrowing behavior for the type(a) == str assignment and the assert(type(a) != str) check. Done means both branches remove str from the inferred Union and the function is accepted with the expected Optional[List[str]] return type.
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
- 35/100