python / python/mypy

Incorrectly inferred type for expression

Aperta
#17,561 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

The type for super().__new__(cls, value) is incorrectly inferred when used outside of __new__.

In the example below I used super().__new__(cls, value) in __init_subclass__ and the inferred type is the base class that defines __init_subclass__ instead of being Self. At the same time within __new__, the same expression is correctly inferred as Self.

To Reproduce

from typing import ClassVar, Self, reveal_type

class LiteralBytes(bytes):
    _instance_: ClassVar[Self] = NotImplemented

    def __init_subclass__(cls, *, value: bytes = NotImplemented, **kw: object) -> None:
        if value is not NotImplemented:
            cls._instance_ = reveal_type(super().__new__(cls, value))
        super().__init_subclass__(**kw)

    def __new__(cls) -> Self:
        reveal_type(super().__new__(cls, b''))  # this is here just to showcase the difference in the inferred type
        if cls._instance_ is NotImplemented:
            raise TypeError(f'Cannot instantiate abstract literal bytes type {cls.__qualname__!r} that does not define its value')
        return cls._instance_

The sample program above is also available here: playground link

Expected Behavior

I expect super().__new__(cls, ...) to always be inferred as Self no matter in which method is called as that expression always produces an instance of cls (as long as cls points to the class, i.e. we are in a class method, inside __new__, ...)

Actual Behavior

main.py:8: error: Incompatible types in assignment (expression has type "LiteralBytes", variable has type "Self")  [assignment]
main.py:8: note: Revealed type is "__main__.LiteralBytes"
main.py:12: note: Revealed type is "Self`0"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.12.0+dev.6aa46f097cf30f3143c5ee4bae7f0d2e7ce914bc (compiled: no)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files):
[tool.mypy]
enable_incomplete_feature = "NewGenericSyntax"
disable_bytearray_promotion = true
disable_memoryview_promotion = true
check_untyped_defs = true
warn_unreachable = true
warn_redundant_casts = true
warn_unused_ignores = true
  • Python version used: 3.12

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 con il reproducer in main.py e traccia come il type checker inferisce super().new(cls, value) al di fuori di new. Confronta quel percorso con l’inferenza all’interno di new. È completato quando l’espressione viene rivelata come Self in entrambe le posizioni e l’assegnazione a instance non segnala più un’incompatibilità.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.