在Dataclass Reader中使用Typing.Literal

发布于 2025-01-19 21:42:26 字数 769 浏览 1 评论 0原文

我有一个CSV文件,我想将其处理到数据级别。我想检查数据集中的成绩仅来自预定列表,如果不是这样,我想记录错误/警告。我的课程看起来如下,

from dataclasses import dataclass
from typing import Literal

grade_options = Literal['1A', '1B', '1C']

class Student:
    name: str
    age: int
    grade: grade_options

我读了我的CSV文件(使用dataclass-csv ),但是实例化此类型存在问题

from dataclass_csv import DataclassReader

with open('students.csv', encoding="utf-8-sig") as read_csv:
    reader = DataclassReader(read_csv, Student, delimiter=";")
    students = [student for student in reader]

,这将导致typeError:无法实例化键入。文字

除了创建手动检查器以查看我的值是否在CSV文件是指定的选项之一?

I have a csv file that I'd like to process to a dataclass. I'd like to check that the grades in my dataset are only from a prespecified list, if this is not the case I'd like to log an error/warning. My class looks as follows

from dataclasses import dataclass
from typing import Literal

grade_options = Literal['1A', '1B', '1C']

class Student:
    name: str
    age: int
    grade: grade_options

I read my csv file (using the dataclass-csv library), yet it has problems to instantiate this type

from dataclass_csv import DataclassReader

with open('students.csv', encoding="utf-8-sig") as read_csv:
    reader = DataclassReader(read_csv, Student, delimiter=";")
    students = [student for student in reader]

This will result in a TypeError: Cannot instantiate typing.Literal

Is there any other option than creating a manual checker to see if my values in the csv file are one of the specified options?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缱倦旧时光 2025-01-26 21:42:26

我自己遇到了这个。您必须使用扩展enum的具体类。

基于“创建枚举类”, a>:

from enum import Enum


class Grade(str, Enum):
    _1a: '1A'
    _1b: '1B'
    _1c: '1C'

class Student:
    name: str
    age: int
    grade: Grade

I just ran into this myself. You have to use concrete classes that extend Enum.

Based on "Create an enum class" in the tutorial:

from enum import Enum


class Grade(str, Enum):
    _1a: '1A'
    _1b: '1B'
    _1c: '1C'

class Student:
    name: str
    age: int
    grade: Grade
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文