pythontype-hintingmetaclass

What's the correct type hint for a metaclass method in Python that returns a class instance?


In the example below, __getitem__ indicates the class type as a hint, rather than return of a SpecialClass object.

from typing import Self

class SpecialMeta(type):
    def __getitem__(cls, key) -> Self:
        ...

class SpecialClass(metaclass=SpecialMeta):
    ...

one = SpecialClass()
# type(one) : SpecialClass

two = SpecialClass["findme"]
# type(two) : type[SpecialClass]

What is the correct type hint to indicate type(two) = SpecialClass instead of type[SpecialClass]? Is there a general way to do this starting around Python 3.8 or so?


Solution

  • As stated in the comment by "@_SUTerliakov - supports strike", this can be done with generics by simply indicating that the generic type goes in, and an instance of it comes out:

    import typing
    
    T_ = typing.Generic()
    
    def __getitem__(cls: type[_T], key: str) -> _T:
        ...
        instance = cls(...)
        ...
        return instance