python / python/typing

[spec] Can staticmethod calls infer type parameters for the containing class?

Open
#1,845 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

In this code:

from typing import TypeVar, Generic
T = TypeVar('T')

class Foo(Generic[T]):
    @staticmethod
    def create(arg: T) -> 'Foo[T]':
        ...

reveal_type(Foo.create(1234))

What should the type be? Should T be inferred based on the argument to the static method, resulting in Foo[int]? Or should it be Foo[Unknown] or similar?

mypy (python/mypy@fe15ee69b) picks Foo[int].

pyright used to choose Foo[int], but microsoft/pyright#7454 changed it to pick Foo[Unknown], on the grounds that this is required to comply with PEP 696's statement:

Type parameter defaults should be bound by attribute access (including call and subscript).

My example does not include any type parameter defaults, but I can see the logic of applying the same rule without one: you wouldn't want it to be a breaking change to add a default.

Still, why can't these kinds of static method calls be treated like constructor calls, where class type parameters can be inferred from arguments?

Contributor guide

No contributing guide indexed for this repository

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 reviewing the example, PEP 696's binding rules, mypy commit fe15ee69b, and the referenced pyright issue. Determine the agreed behavior for staticmethod calls on generic classes and record the resulting specification decision, including whether type checkers should infer Foo[int] or use an unknown type.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.