python / python/mypy

With v1.4 module-global variables become fixed in type.

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

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

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

説明

This seems to be a regression with v1.4 of mypy.

It looks to me like globals are considered constant if they’re not explicitly typed. For example (see issue https://github.com/Bogdanp/dramatiq/issues/555) a module-global variable like

global_broker = None

seems to be typed now as None. Consequently reading that variable and then asserting its value is always false and therefore raises an exception

broker = some.module.global_broker
assert broker is not None  # Previously this worked; now it's considered None and therefore raises.

and that means that the next statement

broker.enqueue(message, delay=delay)

becomes unreachable.

I therefore changed the module-global variable declaration to

global_broker: Optional["Broker"] = None

which solved the problem. However, that’s in an external module and therefore my own code is now broken after updating to v1.4 of mypy.

Would it make sense to consider the type for such a module-global variable as Any | None (or just Any) instead of just None? (Assuming that a module-global None variable will change.)

To Reproduce

See above.

Expected Behavior

As with v1.3 I would have expected mypy to pass the type check.

Actual Behavior

With v1.4 mypy now flags the statement following the assert as unreachable.

Your Environment

  • Mypy version used: mypy 1.4.1
  • Mypy configuration options from mypy.ini (and other config files):
     [tool.mypy]
     show_error_codes = true
     show_column_numbers = true
     check_untyped_defs = true
     incremental = false
     strict_equality = true
     warn_return_any = true
     warn_redundant_casts = true
     warn_unreachable = true
     warn_unused_configs = true
     warn_unused_ignores = true
     disallow_untyped_calls = true
     disallow_untyped_defs = true
     disallow_incomplete_defs = true
     disallow_untyped_decorators = true
     disable_error_code = []
     plugins = "sqlalchemy.ext.mypy.plugin"
    
  • Python version used: 3.10.12

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

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

はじめの一歩

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

調査の方向性

Issue にあるモジュールグローバルの最小 reproducer から始め、記載された設定、特に warn_unreachable と strict_equality を使って mypy 1.3 と 1.4.1 を比較します。None で初期化されたアノテーションなしのグローバル変数の動作が決定され、assert とその後のメソッド呼び出しを含む回帰テストでカバーされれば完了です。

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

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

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

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