python / python/mypy

Assignment to Final attribute incorrectly flagged in conditional assignment within __init__

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

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

bug topic-final
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report

Documentation on typing.Final says (emphasis mine):

Final names cannot be reassigned in any scope. Final names declared in class scopes cannot be overridden in subclasses.

The problem comes in a class's init, if the final member is conditionally assigned to different values (e.g. assignments in an if/else expression, if the assignment to the member occurs in both blocks). In the if/else case, mypy flags the assignment in the else block.

To Reproduce

from typing import Final


class Foo:
    attr: Final[str]

    def __init__(self, flag: bool) -> None:
        if flag:
            self.attr = "bar"
        else:
            self.attr = "baz"  # mypy flags with:  error: Cannot assign to final attribute "attr"  [misc]

Expected Behavior

I would expect mypy to not flag this code at all. For either possible value of flag, there is only a single assignment, so no reassignment occurs.

Actual Behavior

Mypy flags line 11 with: error: Cannot assign to final attribute "attr" [misc]

Your Environment

  • Mypy version used: mypy 1.19.1 (compiled: yes)
  • Mypy command-line flags: none; just the path to the repro test script
  • Mypy configuration options from mypy.ini (and other config files):
[tool.mypy]
python_version = "3.13"

# set mypy_path and explicit_package_bases, otherwise mypy gets confused about package names
# due to the use of namespace packages.
mypy_path = "src"
explicit_package_bases = true

pretty = true
disallow_any_unimported = true
disallow_any_expr = false
disallow_any_explicit = false
disallow_any_generics = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
disallow_untyped_decorators = true
implicit_optional = true
strict_optional = true
warn_redundant_casts = true
warn_unused_ignores = true
warn_no_return = true
warn_return_any = true
warn_unreachable = true
warn_unused_configs = true
exclude = ["dist/.*/.*\\.py$"]
  • Python version used: 3.13.7

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

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

はじめの一歩

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

調査の方向性

提供された Python 再現コードから始め、mypy 1.19.1 で実行して、else 分岐の代入に関する診断を確認します。条件付き代入中の Final 属性の処理を追跡し、この例のリグレッションカバレッジを追加します。完了の条件は、両方の分岐が再代入エラーなしで型チェックを通過することです。

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

評価

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

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

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