Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Enum type #58

Open
swasher opened this issue May 27, 2024 · 2 comments
Open

Support for Enum type #58

swasher opened this issue May 27, 2024 · 2 comments

Comments

@swasher
Copy link

swasher commented May 27, 2024

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?

@dupuyarc
Copy link

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.

@swasher
Copy link
Author

swasher commented May 31, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants