Skip to content

Generic with dataclasses #2763

Answered by erictraut
Andarius asked this question in Q&A
Dec 27, 2021 · 1 comments · 3 replies
Discussion options

You must be logged in to vote

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)

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@Andarius
Comment options

@Andarius
Comment options

@erictraut
Comment options

Answer selected by Andarius
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants