on-internet
← Community

Why can a parameterized class be instantiated?

Stack Overflow ·

I have this generic class: class Box[T]: def __init__(self, val: T): self.val = val In Python < 3.12, that would be written: from typing import TypeVar, Generic T = TypeVar('T') class Box(Generic[T]): def __init__(self, val: T): self.val = val According to the docs, I can instantiate it like this: box = Box[int](42) However, I don't understand why this even works. If I print the type of Box[int]: klass = Box[int] print(type(klass)) # <class 'typing._GenericAlias'> According to the docs and this Q&A, a generic alias is supposed to represent a type annotation by storing the original type and typ

Comments

Sign in or sign up to comment and upvote.

No comments yet.