python / python/mypy

Feature Request: Infer TypeVar Bounds from assert issubclass Statements

Aperta
#17,676 1 commento 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Feature

I would like to request an enhancement in mypy to allow it to infer TypeVar bounds from assert issubclass(...) statements. Currently, mypy uses such assertions for local type refinement within the scope of the assertion, but it does not propagate these refinements globally, particularly for type variables. This leads to cases where developers must manually specify TypeVar bounds, even though the bound could be logically inferred from the assertions in the code.

Use Case:

Consider a scenario where a function takes a Type[T] parameter, and an assert issubclass(cls, MyAbstractClass) check is used to ensure that cls is a subclass of MyAbstractClass. Despite this assertion, mypy does not infer that T is bound by MyAbstractClass, which can lead to type-checking issues where mypy cannot guarantee that cls has the necessary methods or attributes.

Example:

from typing import Type, TypeVar, BinaryIO
from abc import ABC, abstractmethod

class MyAbstractClass(ABC):
    @classmethod
    @abstractmethod
    def from_binary_io(cls, data: BinaryIO) -> 'MyAbstractClass':
        pass

T = TypeVar('T')

def create_instance(cls: Type[T], data: BinaryIO) -> T:
    assert issubclass(cls, MyAbstractClass)
    return cls.from_binary_io(data)

# Example subclass implementation
class MyConcreteClass(MyAbstractClass):
    def __init__(self, content: bytes):
        self.content = content

    @classmethod
    def from_binary_io(cls, data: BinaryIO) -> 'MyConcreteClass':
        content = data.read()
        return cls(content)

In this example, mypy does not infer that T is bound by MyAbstractClass, leading to type-checking issues when calling cls.from_binary_io(data).

Proposed Enhancement:

mypy should be able to infer the bound of T as MyAbstractClass based on the assert issubclass(cls, MyAbstractClass) statement. This enhancement would allow developers to avoid manually specifying bounds for TypeVar when they can be logically deduced from the code.

Pitch

Benefits:

  • Improved Type Inference: Reduces the need for explicit TypeVar bounds, leading to cleaner and more maintainable code.
  • Better Developer Experience: Simplifies code and reduces potential for type-related errors, especially in complex generic scenarios.

Potential Challenges:

  • Implementation Complexity: This feature would require mypy to track and propagate type refinements beyond the local scope, potentially increasing the complexity of type inference.
  • Performance Considerations: Careful consideration would be needed to ensure that this additional type inference does not negatively impact the performance of mypy.

I believe this feature would significantly improve mypy's type inference capabilities and make it even more powerful for developers working with generics and abstract base classes.

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

La issue non indica file di implementazione né test. Inizia riproducendo l’esempio create_instance con mypy, quindi traccia la gestione di assert issubclass(cls, MyAbstractClass) e del raffinamento di TypeVar; il lavoro è completato quando il bound asserito viene propagato a sufficienza affinché cls.from_binary_io(data) superi il controllo dei tipi senza un TypeVar limitato manualmente.

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

Valutazione

Stack tecnologico
python
Ambito
compilers, devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.