Support for Enum type
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?
The README doesn't list Enum as one of the supported types – I vaguely recall some comment about how dataclass+enum+csv didn't work so well, but can't find it now.
You might have more joy using IntEnum although that would likely store numeric values in the CSV, so might not round-trip so well.
You might have more joy using IntEnum although that would likely store numeric values in the CSV, so might not round-trip so well.
Exactly what i want to hear! )
IntEnum is very convinient for me. When I try to write csv, The Status field is saved as an int. That's fine.
Then, I try to load the csv, and get the following 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]
Same as above.
Maybe there is some way to load a csv after all?