Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13891

Generic[T] classmethod implicit type retrieval in Python 3.12

$
0
0

I would like to use the new Python 3.12 generic type signature syntax to know the type of an about-to-be-instantiated class within the classmethod of that class.

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]":        print("I am type {T}!")        return cls()

I've used the advice in the following StackOverflow question to do this for reifying the type within both __new__ and __init__ but I have yet to to figure out a clever way to do this in either a static or class method (ideally a class method).

My goal is to have the following API:

>>> MyClass[int].make_class()"I am type int!"

Or this API (which I don't think is syntactically possible yet):

>>> MyClass.make_class[int]()"I am type int!"

Where in either case, the returned instance would have int bound to the class variable so I can use it later.

MyClass[int].make_class().kind is int == True

I am open to "hacks" (including heavy use of inspect).


Viewing all articles
Browse latest Browse all 13891

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>