Skip to content

Class is not generic if it extends type[X] #100246

Open
@sobolevn

Description

@sobolevn

Code sample:

>>> from typing import TypeVar
>>> X = TypeVar('X')

>>> class Subtype(type[X]): ...
... 
>>> Subtype[int]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'Subtype' is not subscriptable

This is quite strange. To make it generic, you must have explicit Generic base class:

>>> from typing import Generic
>>> class Subtype(type[X], Generic[X]): ...
... 
>>> Subtype[int]
__main__.Subtype[int]

It looks like a bug to me because of two reasons:

  1. Because other stdlib generics work differently:
>>> class Sublist(list[X]): ...
... 
>>> Sublist[int]
  1. Because typing.Type works as it should:
>>> from typing import Type
>>> class Subtype(Type[X]): ...
... 
>>> Subtype[int]
__main__.Subtype[int]

But, I think that type is special enough to be handled extra carefully:

  • class S(type): ... is not generic and does not have __class_getitem__, has type in mro
  • class S(type[X]): ... is generic and has __class_getitem__, has type in mro

I can work on a fix if others agree that this is a bug 😊

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions