python / python/mypy

MyPy not inferring type from assert statement.

Open
#16,790 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

MyPy is not inferring the right type after an assert statement.

To Reproduce

assert my_options is None or isinstance(my_options.options, CustomOptions)
return MyClass(
        options=my_options.options if my_options else None
)

my_options.options can be CustomOptions or AnotherCustomOptions, but MyClass supports only CustomOptions.

Actual Behavior

error: Argument "options" to "MyClass" has incompatible type "Union[CustomOptions, AnotherCustomOptions, None]"; expected "Optional[CustomOptions]"  [arg-type]

Your Environment

  • Mypy version used: 1.3.0
  • Mypy command-line flags: --config-file mypy.ini
  • Mypy configuration options from mypy.ini (and other config files):
[mypy]
strict = true
plugins = sqlalchemy.ext.mypy.plugin
mypy_path = $MYPY_CONFIG_FILE_DIR/stubs/
  • Python version used: 3.11.6

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 with the provided Python reproducer under mypy 1.3.0 and the stated strict configuration, then trace how the assert and conditional expression are analyzed. Add a regression test for this narrowing scenario and verify that mypy produces the intended type result without the reported incompatible-type error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.