[Python] Generic[T] class with access to type parameter of classmethod in Python 3.12

Discussão em 'Python' iniciado por Stack, Setembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    Similar to how one could retrieve a type from a generic class type signature via a class method, I am now interested in doing the same for the class method's type signature itself.

    For example, I would like to print the concrete type of T in this example:

    class MyClass[T]:
    kind: type[T]

    @classmethod
    def make_class[T](cls) -> "MyClass[T]":
    instance = cls()
    instance.kind = ...
    print(instance.kind)
    return instance


    Currently this would result in an exception:

    >>> MyClass.make_class[int]()
    TypeError: 'method' object is not subscriptable


    A custom "classmethod" decorator would be ideal as I imagine it would require the least amount of "hacking" to the way generic classes work.

    class MyClass[T]:
    kind: type[T]

    @typed_classmethod
    def make_class[T](cls) -> "MyClass[T]":
    ...

    Continue reading...

Compartilhe esta Página