python / python/mypy

and expression with bool() does not work with Optionals

Open
#5,540 4 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature priority-2-low topic-strict-optional
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.