Ignore incompatible type error when variable is checked in if statement
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
I'm using mypy for type checking in my Python projects and I've come across a situation where I believe mypy could be improved.
Consider the following code:
def foo1(a: str): ...
def foo2(a: str | None, b: str | None):
if not a and not b:
return None
if not a:
return foo1(b)
return None
In this case, mypy raises an error:
Argument 1 to "foo1" has incompatible type "str | None"; expected "str" [arg-type].
However, the function foo1 is only called when b
is not None, so in practice, there is no type error.
The logic of the function ensures that b cannot be None when foo1(b) is called.
This is because in the first if statement, we check if both a and b are None.
If they are not, we proceed to the next if statement where we check if a is None.
If a is None, then b must not be None because of the previous check.
Therefore, foo1(b) is only called when b is not None.
Versions
Python: 3.10.10
MyPy: 1.7.1
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 mypy on the supplied Python reproducer and tracing how the two if statements affect type narrowing. Identify the relevant type-checking tests or entry point, then add a regression case for this control flow. Done means mypy accepts foo1(b) without an arg-type error while preserving existing checks.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100