Skip to content

(🎁) Add a StubOnlyBase decorator for types that don't actually extend things, but do in the stubs (like Generic) #956

Open
@KotlinIsland

Description

@KotlinIsland

There are existing classes that extend things in an abstract way, like ABCs, and things that are Generic in theory but not in reality, for example all the collections (the collection classes are not Generics, they define __class_getitem__) and some are still not subscribe-able but state they are in the stubs, for instance _collections_abc.dict_keys or any of the collections pre 3.9.

It could be used something like:

# _collections_abc.pyi
@StubOnlyBase(KeysView[_KT_co], Generic[_KT_co, _VT_co])
class dict_keys:
    ...
# typing.pyi

@StubOnlyBase(Generic[_T])
class Container:
    if sys.version_info >= (3, 9):
        def __class_getitem__(???) -> ???:

@StubOnlyBase(Collection[_KT], Generic[_KT, _VT_co])
class Mapping(Collection):
    ...

Mapping doesn't actually extend Generic, but Container defines __class_getitem__, so that would also need to be updated in the stubs.

This might help resolve python/mypy#3186, but still indicate that it's not actually one of the bases.

# builtins.pyi
@StubOnlyBase(numbers.Integral)
class int:
    ...

I think a change like this would make the stubs much more understandable and closer to the actual implementation, also fixing issues about older python versions not working properly with the current stubs(python/mypy#11529).

I personally find it very confusing when referencing the stubs that the bases are often false.

No idea how this would be used in a real life annotation, but a workaround that works is:

from typing import _alias  # type: ignore[attr-defined]
from typing import TYPE_CHECKING
from _collections_abc import dict_keys

if not TYPE_CHECKING:
    dict_keys = _alias(dict_keys, 2)

def foo(dk: dict_keys[str, int]) -> None: ...

python/typeshed#6312 (comment)
python/typeshed#6257

Obligatory shill to #953, which I think would render this moot.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions