python / python/mypy

Mypy fails to resolve a less specific `TypeVar` in higher-order functions.

Aperta
#13,234 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-type-variables
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

Mypy fails to resolve a less specific TypeVar to a common subtype of arguments when in a higher-order function call.

For context: #22532

To Reproduce

(Example from @andersk)

from typing import Callable, TypeVar

T = TypeVar("T")
def f(g: Callable[[], T], x: T) -> T:
    return x

x: object = 1
y: object = f(object, x)  # ok
z: object = f(object, 1)  # error: Argument 1 to "f" has incompatible type "Type[object]"; expected "Callable[[], int]"

Expected Behavior

z: object = f(object, 1)

When resolving the arguments in f(object, 1), mypy should bind object to T. Given that the type of object (Callable[[], object]) is a subtype of Callable[[], object] and the type of 1 is a subtype of object, this should be accepted.

Actual Behavior

z: object = f(object, 1)  # error: Argument 1 to "f" has incompatible type "Type[object]"; expected "Callable[[], int]"

Instead of using the less specific object, mypy determines that T -> int and refuses to resolve it as object.

Your Environment

  • Mypy version used: 0.961
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files): strict = true
  • Python version used: 3.8
  • Operating system and version: Ubuntu 20.04

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia riproducendo l’esempio fornito di funzione di ordine superiore con mypy 0.961, Python 3.8 e strict=true. Analizza come l’inferenza di TypeVar gestisce gli argomenti Callable e interi, quindi verifica che la chiamata che usa object venga accettata senza l’errore di incompatibilità segnalato.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
42/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.