python / python/mypy

Unexpected Overloading overlap if String Literal is used within Sequence/Iterable/Collection

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

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

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

説明

Bug Report

If I have a function that accepts a String Literal and Sequence of String Literal and want to overload this function for these two cases, mypy always returns:

Overloaded function signatures 1 and 2 overlap with incompatible return types [misc]

from typing import overload, Literal

@overload
def over(bar: Literal["bar"]) -> int:  # Overloaded function signatures 1 and 2 overlap with incompatible return types  [misc]
    ...

@overload
def over(bar: Sequence[Literal["foo"]]) -> str:
    ...   

def over(bar: Literal["bar"]|Sequence[Literal["foo"]]) -> str|int:
    if bar == "bar":
        return 0
    return ", ".join(bar)
    

To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&gist=d28d528c0765dc0a4a004c360a4008a4

Expected Behavior

No error, as if we would use a list instead:

@overload
def load(bar: Literal["bar"]) -> int:
    ...

@overload
def load(bar: list[Literal["foo"]]) -> str:
    ...   

def load(bar: Literal["bar"]|list[Literal["foo"]]) -> str|int:
    if bar == "bar":
        return 0
    return ", ".join(bar)

Actual Behavior
Mypy returns:

Overloaded function signatures 1 and 2 overlap with incompatible return types [misc]

Your Environment

MyPy playground....

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

Note
I am aware that a str is also a Sequence[str]. But as we using literals here, this shouldn't matter.

This is only an issue for mypy if used with overloads, it works correctly if simply used within a function

# Simple example, that if we use Sequences and Literals, mypy
# can determine stuff correctly
def foo(bar: Literal["bar"]|Sequence[Literal["foo"]]) -> None:
    return None
    
    
foo("bar")  # okay
foo(["foo"]) # okay
foo("foo") # not okay - as expected
foo(["bar"]) # not okay - as expected

Note that pyright does detect the overloads correctly (kind of).

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

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

はじめの一歩

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

調査の方向性

まず、リンクされている mypy-play の再現例を実行し、Sequence、Iterable、Collection、list を使用する overload の例を、最後に行われる関数呼び出しのチェックと比較します。報告された診断に関係する overload の互換性と Literal の扱いを追跡します。String Literal とシーケンスの有効な overload が非互換な重複エラーを生成しなくなり、無効な呼び出しは引き続き拒否されれば完了です。

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

評価

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

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

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