Skip to content

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

@comex

Description

@comex

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions