[Python] "ReturnType Error" in Pylance with covariance and type parameter constraints

Discussão em 'Python' iniciado por Stack, Agosto 5, 2025.

  1. Stack

    Stack Membro Participativo

    In Python 3.13.3, I encountered a type-checking issue with Pylance when using generics with type constraints and AsyncIterable. Here's the code snippet that raises the error:

    from collections.abc import AsyncIterable


    class Chunk: ...


    class Foo[Dlt: Chunk | str]:
    def run(self) -> AsyncIterable[Chunk]: ...

    def process(self) -> AsyncIterable[Dlt]:
    return self.run() # ReturnType Error


    The following error is reported by Pylance for the return self.run() line:

    Expression of type "AsyncIterable[Chunk]" cannot be assigned to the return type "AsyncIterable[Dlt@Foo]"
    "AsyncIterable[Chunk]" is incompatible with "AsyncIterable[Dlt@Foo]"
    Type variable "_T_co@AsyncIterable" is covariant, so "Chunk" cannot be assigned to "Dlt@Foo"
    Type "Chunk" cannot be assigned to type "Dlt@Foo" Pylance(reportReturnType)

    What I Have Tried:


    To address the issue, I have tried the following approaches, but none of them resolved the error:

    1. Changing the constraint to a stricter one, e.g., class Foo[Dlt: Chunk]:
    2. Rewriting the generic parameter using TypeVar instead of PEP 695 syntax.
    3. With the TypeVar syntax:
      • Enabling covariance or contravariance for Dlt.
      • Using bound: TypeVar('Dlt', bound = Chunk | str).
      • Using constraint: TypeVar('Dlt', Chunk, str)

    Despite these variations, Pylance continues to raise the same error.

    Key Questions:

    1. Why does Pylance raise this error even though Dlt is constrained to Chunk | str and run() returns AsyncIterable[Chunk]?
    2. Is this issue related to the covariance of the type parameter in AsyncIterable?
    3. How can I resolve the type mismatch error while keeping process() generic and type-safe?

    Any insights, explanations, or alternative approaches are greatly appreciated!

    Continue reading...

Compartilhe esta Página