Not None narrowing doesn't always work for nested field with list comprehensions

オープン
#13,719 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
45/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
停滞
技術スタック
python
領域
compilers

調査の方向性

提供された dataclass と list-comprehension の例を最初の再現として使用し、複数の条件がある場合に mypy が属性をどのように絞り込むかを追跡してください。このケースの regression test を追加し、mypy がフィルタリングされたリスト要素の返却をエラーなしで受け入れることを確認してください。

索引モデルが issue の本文から書いたものです。

説明

feature topic-type-narrowing

Bug Report

When a list comprehension is used to filter class instances with some property not None and another condition, mypy doesn't later infer that instances from that list has a not None value for the property.

To Reproduce

  1. Write this code:
@dataclass
class HasOptionalField:
    is_default: bool
    field: str | None


def first_not_none_field(models: list[HasOptionalField]) -> str:
    models_without_none = [model for model in models if model.is_default and model.field is not None]
    return models_without_none[0].field
  1. Run mypy on above code with below settings

Expected Behavior

Mypy should pass without errors

Actual Behavior

Mypy has error: Incompatible return value type (got "Optional[str]", expected "str") [return-value]
When removing the model.is_default condition and keeping just model.field is not None then mypy doesn't emit errors.

Your Environment

  • Mypy version used: 0.971
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files):

follow_imports = "normal"
ignore_errors = false
implicit_reexport = false
warn_redundant_casts = true
warn_unused_ignores = true
disallow_any_generics = true
disallow_untyped_defs = true
check_untyped_defs = true
allow_redefinition = false
local_partial_types = true
strict_optional = true
strict_equality = true
warn_unused_configs = true
warn_unreachable = true
warn_no_return = true
no_implicit_optional = true
strict = true

  • Python version used: 3.10.4
  • Operating system and version: Windows 11
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

python/mypy のほかの issue

python/mypy の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。