8000 [Question] why covariant type variable isn't allowed in instance method parameter? · Issue #7049 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content
[Question] why covariant type variable isn't allowed in instance method parameter? #7049
@iTakeshi

Description

@iTakeshi

I want define a generic class which is covariant with its type parameter, but mypy claims that covariant type parameter in instance method definition is not allowed.

from typing import Generic, List, TypeVar

T = TypeVar("T", covariant=True)

class GenericClass(Generic[T]):
    def __init__(self) -> None:
        self.list: List[T] = []

    def print(self, arg: T) -> None: # <<< mypy raises error on the "T"; Cannot use a covariant type variable as a parameter
        self.list.append(arg)
        print(self.list)

if __name__ == "__main__":
    g: GenericClass[int] = GenericClass()
    g.print(1)

Is there any solution to get around this?

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

      0