Skip to content

Generic Self Type #2537

Closed
Closed
@jboning

Description

@jboning

This is a followup issue to #1212. #2193 enabled method type annotations to refer to the type of self, but (intentionally) didn't address generic classes. In many cases, the self types added there meet the needs of generic classes, but not always.

A motivating example is typeshed's AbstractClass:

class AbstractSet(Sized, Iterable[_T_co], Container[_T_co], Generic[_T_co]):
    def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ...
    def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ...

With #2193 we can annotate __and__, and it works beautifully:

    def __and__(self: SelfT, s: AbstractSet[Any]) -> SelfT: ...
def f(s, fs):
    # type: (MutableSet[str], FrozenSet[str]) -> None
    reveal_type(s.__and__)  # Revealed type is 'def (typing.AbstractSet[Any]) -> typing.MutableSet[builtins.str]'
    reveal_type(fs.__and__)  # Revealed type is 'def (typing.AbstractSet[Any]) -> typing.FrozenSet[builtins.str]'

But, we don't have the tools to give __or__ a similarly specific type. To do this, we need some way to talk about the "generic" part of the self type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions