python / python/mypy

Covariant type variables should be allowed in class method

Open
#6,178 20 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature priority-1-normal
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Currently, covariant type variables are allowed in __init__ so that you can put create an immutable containers with something inside of it. See https://github.com/python/mypy/issues/2850.

It would be useful if covariant types are also allowed in class method that serve as alternative constructors. Currently mypy errors on this example, which is an extension of the other issues example:

from typing import Generic, TypeVar

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


class C(Generic[T_co]):
    def __init__(self, x: T_co) -> None:
        ...

    @classmethod
    def custom_init(cls, x: T_co) -> "C[T_co]":
        # error: Cannot use a covariant type variable as a parameter
        return cls(x)

My use case is trying to define an immutable container protocol that has a create class method, which will initialize the container with some contents, like this:

T_cov = typing.TypeVar("T_cov", covariant=True)

class ListProtocol(typing_extensions.Protocol[T_cov]):
    @classmethod
    def create(cls, *items: T_cov) -> "ListProtocol[T_cov]":
        ...

    def getitem(self) -> T_cov:
        ...
    
    ...

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue with the classmethod examples in the report and inspect how mypy validates covariant type variables in method parameters. Define the intended behavior for alternative constructors, then add regression coverage showing the accepted cases and run the relevant type-checker tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.