python / python/mypy

Wrong return type inferred for overload with a type variable

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

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

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

説明

Bug Report

from typing import TypeVar, overload

_T = TypeVar("_T")

@overload
def getenv(key: str) -> str | None: ...

@overload
def getenv(key: str, default: _T) -> str | _T: ...

def getenv(key, default):
    return key


def test(custom_var: str) -> str:
    return getenv(custom_var) or getenv("V", "D")

https://mypy-play.net/?mypy=latest&python=3.12&gist=4d959cd7069a8495533bfeca1cd40729

Actual Behavior

main.py:16: error: Incompatible return value type (got "str | None", expected "str")  [return-value]

Expected Behavior

This should type check without errors, since we have an or with a call that always returns str.

It works if I replace type variable with just str:

@overload
def getenv(key: str, default: str) -> str: ...

but something about _T and the union upsets it.

Your Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10-3.13

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

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

はじめの一歩

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

調査の方向性

提供された Python の再現コードから始め、設定フラグなしで mypy 1.13.0 を使用して動作を確認してください。2 つの getenv 呼び出しについて、オーバーロード解決と型変数の推論を追跡し、その後、fallback が str を返す場合に式が受け入れられることを示す回帰テストを追加してください。

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

評価

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

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

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