Skip to content

The error message caused by setting the covariant type variable of TypeVar to functions should be more specific #20360

@hyperkai

Description

@hyperkai

*Memo:

  • mypy --strict test.py
  • mypy 1.18.2
  • Python 3.14.0
  • Windows 11

Setting the covariant type variable of TypeVar to functions' parameters gets the error message except for __init__, __new__, and instance method's self as shown below:

from typing import TypeVar, Generic, cast, Type

class MyCls(Generic[T]):

               # ↓↓↓↓↓↓↓↓↓↓↓↓↓ No error
    def __init__(self: T, x: T) -> None: ...
               
              # ↓↓↓↓↓↓↓↓↓↓↓↓ No error
    def __new__(cls: T, x: T) -> MyCls[T]:
        instance = super().__new__(cast(Type[MyCls[T]], cls)) 
        return instance

           # ↓↓↓↓↓↓↓ No error
    def ins1(self: T) -> None: ...
     
                 # ↓↓↓↓ Error
    def ins2(self, x: T) -> None: ...

    @classmethod            
    def cls(cls: T, x: T) -> None: ...
          # ↑↑↑↑↑↑↑↑↑↑↑↑ Error

    @staticmethod            
    def sta(x: T) -> None: ...
          # ↑↑↑↑ Error

def func(x: T) -> None: ...

error: Cannot use a covariant type variable as a parameter

So, the error message should be more specific like below:

error: Cannot use a covariant type variable as a parameter except for __init__, __new__, and instance method's self

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongpendingIssues that may be closed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions