python / python/mypy

Using `classmethod` of generic alias of a generic type and `--disallow-any-generics`

Open
#16,982 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic-inference topic-type-alias
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Code:

from typing import TypeVar, Generic, reveal_type

T = TypeVar('T')
N = TypeVar('N')

class My(Generic[T]):
    def __init__(self, arg: T) -> None:
        self.arg = arg
    @classmethod
    def from_arg(cls, arg: N) -> 'My[N]':
        return My(arg)
        

Alias = My[T]
        
reveal_type(My.from_arg(1)) 
# note: Revealed type is "__main__.My[builtins.int]"

reveal_type(Alias.from_arg(1))
# error: Missing type parameters for generic type "Alias"  [type-arg]
# note: Revealed type is "__main__.My[builtins.int]"

Link: https://mypy-play.net/?mypy=latest&python=3.12&flags=disallow-any-generics&gist=f657946226b54d0654952c6bcdb02a61

Problem: I think that [type-arg] error should not be raised in this case, because no type param is actually needed in this case. classmethod is often used as a constructor, duplicating type vars is verbose and unneeded.

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 example in the linked mypy-play case with --disallow-any-generics, then trace how generic aliases and classmethod calls are analyzed. Done means Alias.from_arg(1) no longer raises the type-arg error while its revealed type remains My[int].

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.