Skip to content

use type context to inform default specialization of bare generic class name #1624

@carljm

Description

@carljm

Example code (derived from psycopg2):

from typing import TypeVar, Generic

Row = TypeVar("Row", default=int)

class Cursor(Generic[Row]):
    x: Row

class Connection(Generic[Row]):
    factory: type[Cursor[Row]]

    def __init__(self):
        reveal_type(Cursor)
        self.factory = Cursor

We default-specialize Cursor in the last line, leading to treating it as <class 'Cursor[int]'>, which is not assignable to type[Cursor[Row]] (since Row is a typevar in the scope of class Connection -- the assignment must be valid for any possible specialization of Connection).

Mypy and pyright both allow this assignment, and it seems like they use bidirectional typing (type context) to do so (evidence: making the last line self.factory = reveal_type(Cursor) makes it fail in pyright). So perhaps type context should take precedence over typevar defaults when deciding how to implicitly specialize in this case.

Metadata

Metadata

Assignees

Labels

bidirectional inferenceInference of types that takes into account the context of a declared type or expected typegenericsBugs or features relating to ty's generics implementation

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions