and expression with bool() does not work with Optionals
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
For the following code, mypy reports an incompatible type error on the function f
from typing import Optional
def f(x:Optional[str]) -> bool:
return bool(x) and g(x)
def f2(x:Optional[str]) -> bool:
if x:
return g(x)
return False
def g(x: str) -> bool:
return bool(x)
test.py:4: error: Argument 1 to "g" has incompatible type "Optional[str]"; expected "str"
however the code is equivalent to the one in f2, for which no error is raised.
-
What are the versions of mypy and Python you are using?
Mypy: 0.620, Python: 3.6.5 -
What are the mypy flags you are using? (For example --strict-optional)
[mypy]
# This flag should be removed here and enabled per module when we have a
# considerable number of stubs for external libraries.
ignore_missing_imports = True
strict_optional = True
warn_unused_ignores = True
warn_redundant_casts = True
warn_unused_configs = True
check_untyped_defs = True
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 reported minimal reproducer with strict_optional enabled and compare the diagnostics for f and f2. Trace mypy's handling of the bool(x) and g(x) expression and its narrowing of Optional[str]. Done means the equivalent f function is accepted without the incompatible-type error while the existing f2 behavior remains valid.
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
- Clearly specified
- Newbie friendliness
- 42/100