-
I would like to define a holder of a user defined type like so: class Box(Generic[T]):
def __init__(self, datatype: type[T]):
self.datatype = datatype
self.value: Optional[T] = None
def set(self, value: T):
self.value = value but I would like to constrain the datatype to be I thought that defining T = TypeVar("T", int, str, Enum, LiteralString) might do the trick, but it fails on
Is there a way to achieve this? Code sample in pyright playground |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You're attempting to use a value-constrained TypeVar here. I generally recommend avoiding these if possible. They are poorly specified in the typing spec and have many unusual and surprising behaviors and limitations. This concept is unique to Python and doesn't appear in other programming languages that support generics. There's a good reason for this. In your code sample, you're defining a TypeVar that includes a value constraint of Another issue here is that you're attempting to pass the runtime value for a type expression ( There is a draft PEP 747 that provides a way to annotate a parameter that accepts runtime values evaluated from type expressions, but it has not yet made its way through the spec'ing and approval process. I'm not able to offer you any specific advice about how to write your proposed |
Beta Was this translation helpful? Give feedback.
You're attempting to use a value-constrained TypeVar here. I generally recommend avoiding these if possible. They are poorly specified in the typing spec and have many unusual and surprising behaviors and limitations. This concept is unique to Python and doesn't appear in other programming languages that support generics. There's a good reason for this.
In your code sample, you're defining a TypeVar that includes a value constraint of
str
andLiteralString
, butLiteralString
is a subtype ofstr
. AllLiteralString
values are already legal values of the typestr
, so that's an immediate red flag.Another issue here is that you're attempting to pass the runtime value for a type expression (
Li…