python / python/mypy

Limited inference with union of callables and assignment to a union

Offen
#18,191 4 Kommentare 18 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-type-context
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

Apologies if this was raised already. The only related issue I could find is https://github.com/python/mypy/issues/15887.

In Pydantic 2.10, we changed the definition of our field function to be:

from typing import Callable, TypeVar

_T = TypeVar('_T')

def Field(
    *,
    default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
) -> _T: ...

While this type checks correctly for some common use cases, we get errors when the Field function is assigned to a union of types, or when the default factory signature isn't trivial (e.g. contains overloads). Here are some examples failing:

(playground)

EDIT: Seems like the issue was fixed since 1.16.0. The issue with Class.b remains:

cvar = ContextVar[None]("session_id", default=None)


class Class:
    # error: Argument "default_factory" to "Field" has incompatible type "type[list[Any]]"; expected "Callable[[], Never] | Callable[[dict[str, Any]], Never]"  [arg-type]:
    a: list | None = Field(default_factory=list)

    # error: Argument "default_factory" to "Field" has incompatible type overloaded function; expected "Callable[[], Never] | Callable[[dict[str, Any]], Never]"  [arg-type]:
    b: None = Field(default_factory=cvar.get)  # note that `cvar.get` is overloaded. The first overload (`() -> None`) should match.


    # fine:
    fine: list = Field(default_factory=list)

Note that (at least for a), this worked as expected with the old type inference.

I first wanted to know if this can be considered a mypy limitation, or is the code really unsafe in some way? Or maybe is it because the typing spec does not provide any info regarding these use cases?

In comparison, pyright and pyre accepts the provided examples. We will currently recommend users to add a type: ignore comment and redirect to this issue. However, feel free to close if there's already an issue tracking this.

Thanks in advance

Your Environment

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit dem bereitgestellten Python-3.13-Reproducer und dem verknüpften Playground und konzentriere dich auf den verbleibenden Fall Class.b, in dem ContextVar.get überladen ist und an Field übergeben wird. Vergleiche das Verhalten mit der im Bericht beschriebenen alten Inferenz und füge anschließend einen Regressionstest hinzu, der zeigt, dass die erste () -> None-Überladung ohne ein type: ignore akzeptiert wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.