python / python/mypy

Assignment to Any doesn't make it more precise

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

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

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

説明

  • Are you reporting a bug, or opening a feature request?

Bug report.

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
from typing import Any, Optional


def foo(baz: Any) -> int:
    return 1


def bar1(baz: Any = 0) -> int:
    reveal_type(baz)
    baz = foo(baz)
    reveal_type(baz)
    return baz


def bar2(baz: Optional[Any] = 0) -> int:
    reveal_type(baz)
    baz = foo(baz)
    reveal_type(baz)
    return baz
  • What is the actual behavior/output?
main.py:9: note: Revealed type is 'Any'
main.py:11: note: Revealed type is 'Any'
main.py:12: error: Returning Any from function declared to return "int"
main.py:16: note: Revealed type is 'Union[Any, None]'
main.py:18: note: Revealed type is 'builtins.int'
Found 1 error in 1 file (checked 1 source file)
  • What is the behavior/output you expect?

After baz = foo(baz) the type of baz should be int. Redefinition should not be a problem here since this assignment makes the type of baz more precise.

By trial-and-error I found that annotating bar as a Union of Any and anything else (here Optional[Any] == Union[Any, None]) fixes this behavior.

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

mypy: 0.780 / 0.790+dev.95eff27adb1fae7b1ec4a7315524ebfdcebf6e2b
python: 3.6.9

  • What are the mypy flags you are using? (For example --strict-optional)

--warn-return-any

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

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

はじめの一歩

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

調査の方向性

main.py として示されている最小の再現例から始め、--warn-return-any を指定して mypy を実行し、baz = foo(baz) の前後で reveal_type の出力を比較します。完了条件は、代入によって baz が int に絞り込まれるものとして扱われ、return-any エラーが報告されなくなる一方で、既存の Optional[Any] の挙動も引き続き理解されていることです。

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

評価

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

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

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