0

I understand that type hints are constructs during compilation, but is there a way to access them during object construction? For instance

T = typing.TypeVar("T")
class Foo(typing.Generic[T]):
    pass

If someone now writes Foo[int], is there a way to access int in Foo's __init__ method?

JRR
  • 6,014
  • 6
  • 39
  • 59
  • There's funky stuff you can do to try to examine the `__args__` of the class object, but in practice it's easier to sidestep the issue by making sure that your class takes a parameter of type `T` so that you can just look at *that* at runtime. – Samwise Jun 25 '23 at 00:08
  • You should not do this, because such "clever" type hint usage will make a huge pain for your users. Static analysis aside, remember that fancy `from __future__ import annotations`? Any users who use this (or need string type annotations somewhere - maybe due to version incompatibility or stub-only types) will break your code, because you'll see a string and not a type (the string may not be a fully qualified ident, and even if it is - it may be not importable). Are you ready to support other typevars in generic? Or NewType? Just add `__init__` accepting instance of `T` or type `T` itself. – STerliakov Jun 25 '23 at 00:41
  • And you certainly will not have access to generic parameter in `__init__` - it is erased earlier. Check `__args__` (or better `typing.get_args`) to see that - instances never have those set to anything but empty tuple, and this is by design. Generic in python are static analysis helpers, not intended for runtime usage. – STerliakov Jun 25 '23 at 00:45
  • 1
    Does this answer your question? [Generic\[T\] base class - how to get type of T from within instance?](https://stackoverflow.com/questions/57706180/generict-base-class-how-to-get-type-of-t-from-within-instance) – Daniil Fajnberg Jun 25 '23 at 14:32

0 Answers0