-
I have the following dataclass with a generic property and I'm not sure on how to go with this. I have the from typing import Union, Any, TypeVar, Generic
from dataclasses import dataclass
PossibleTypes = Union[str, int, float]
def validate_type(data_type: Any, value: str) -> PossibleTypes:
if data_type is str:
return str(value)
elif data_type is int:
return int(value)
elif data_type is float:
return float(value)
else:
raise NotImplementedError()
T = TypeVar('T', str, int, float)
@dataclass
class CommandOption(Generic[T]):
data_type: T
def validate(self, value: str) -> T:
return validate_type(self.data_type, value) But it raises:
What is the correct way of typing either Thanks ! |
Beta Was this translation helpful? Give feedback.
Answered by
erictraut
Dec 27, 2021
Replies: 1 comment 3 replies
-
I'm not 100% sure I understand what you're trying to do here, but if my assumptions are correct, here's a potential solution: from typing import TypeVar, Generic
from dataclasses import dataclass
T = TypeVar("T", str, int, float)
def validate_type(data_type: type[T], value: str) -> T:
if data_type in T.__constraints__:
return data_type(value)
raise NotImplementedError()
@dataclass
class CommandOption(Generic[T]):
data_type: type[T]
def validate(self, value: str) -> T:
return validate_type(self.data_type, value) |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
Andarius
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not 100% sure I understand what you're trying to do here, but if my assumptions are correct, here's a potential solution: