Skip to content

Covariant type variables should be allowed in __init__ #2850

Closed
@ilevkivskyi

Description

@ilevkivskyi

There are several issues about covariance, but I didn't find any discussion about __init__. Currently, mypy complains about this code:

from typing import Generic, TypeVar

T_co = TypeVar('T_co', covariant=True)

class C(Generic[T_co]):
    def __init__(self, x: T_co) -> None:
       # Error: Cannot use a covariant type variable as a parameter
       ...

Although this is normal in general, I believe this should be allowed for __init__. Otherwise it would be difficult (if possible at all) to put something into a covariant (immutable) container on instantiation.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions