Skip to content

Bounding a TypeVar to a Protocol #7212

@huzecong

Description

@huzecong

Are you reporting a bug, or opening a feature request?

Feature request.

Please insert below the code you are checking with mypy,
or a mock-up repro if the source is private. We would appreciate
if you try to simplify your case to a minimal repro.

class Example(Protocol):
    sentence: List[str]

T = TypeVar('T', bound=Example)

class Dataset(Generic[T]):
    ....

class ConcreteExample(NamedTuple):
    sentence: List[str]
    others: Any

class ConcreteDataset(Dataset[ConcreteExample]):
    ....

What is the actual behavior/output?

On the line defining ConcreteDataset, mypy gives an error that the type ConcreteExample is not a subtype of Example.

What is the behavior/output you expect?

mypy is correct in the error, but I would like a way to bound the TypeVar to a Protocol such that classes satisfying the protocol would not have to subclass it. For instance, in the previous example, it is not possible to subclass Example because ConcreteExample is a NamedTuple. I also feel that it's against the original motivation of Protocol to require some class to subclass it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions