在Dataclass Reader中使用Typing.Literal
我有一个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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己遇到了这个。您必须使用扩展
enum
的具体类。基于“创建枚举类”, a>:
I just ran into this myself. You have to use concrete classes that extend
Enum
.Based on "Create an enum class" in the tutorial: