Skip to content

Support for Enum type #58

@swasher

Description

@swasher

Is it possible to read/write datas represented as Enum class?

I write some demo code:

from dataclasses import dataclass
from enum import Enum
from dataclass_csv import DataclassWriter, DataclassReader

class Status(Enum):
    PLANNED = 0
    IN_PROGRESS = 1
    DONE = 2

@dataclass
class Job:
    name: str = None
    status: Status = None

jobs = [
    Job('first', Status.PLANNED),
    Job('second', Status.IN_PROGRESS),
    Job('third', Status.DONE)
]

with open("jobs.csv", "w") as f:
    w = DataclassWriter(f, jobs, Job, lineterminator='\n')
    w.write()

At this point we have valid CSV. Notice that Enum class writed as constant's names:

name,status
first,Status.PLANNED
second,Status.IN_PROGRESS
third,Status.DONE

Then I try to read that csv:

with open("jobs.csv") as jobs_csv:
    reader = DataclassReader(jobs_csv, Job)
    for row in reader:
        print(row)

and got error:

dataclass_csv.exceptions.CsvValueError: The field `status` is defined as <enum 'Status'> but received a value of type <class 'str'>. [CSV Line number: 2]

Аs said in the error description, we have conflict beetween datatypes.
Is it possible to read/write enum datas in this manner? If not, can I ask for this functionality as feature request?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions