0

I just started to use dataclasses. I have created a python dataclass:

from dataclasses import dataclass, fields
from typing import Optional


@dataclass
class CSVData:
    SUPPLIER_AID: str = ""
    EAN: Optional[str] = None
    DESCRIPTION_SHORT: str = ""
    DESCRIPTION_LONG: str = "Article long description"

After creating an instance of a this dataclass and printing it out:

data = CSVData(SUPPLIER_AID='1234-568',
               EAN='EAN number',
               DESCRIPTION_SHORT='Article Name')

print(data)

output is:

CSVData(SUPPLIER_AID='1234-568', EAN='EAN number', DESCRIPTION_SHORT='Article name', DESCRIPTION_LONG='Article long description')

When i call the fields function:

for field in fields(data):
    print(field.default)

output is:

"", None, "", Article long description

I would expect to print: 1234-568, EAN number, Article Name, Article long description

3
  • The default value of the field is not the same as the current value of the object… Commented Nov 27, 2022 at 7:50
  • I've thought that after the object instantiation, the default values are overwritten. Commented Nov 27, 2022 at 8:07
  • 1
    The “field” defines the name and type in general, and the default value is the value it’s going to hold if no argument was given for the instance. The field definition is independent of a concrete instance of the class. Commented Nov 27, 2022 at 8:09

1 Answer 1

3

This is how the dataclass.fields method works (see documentation). If you want to iterate over the values, you can use asdict or astuple instead:

from dataclasses import dataclass, asdict
from typing import Optional


@dataclass
class CSVData:
    SUPPLIER_AID: str = ""
    EAN: Optional[str] = None
    DESCRIPTION_SHORT: str = ""
    DESCRIPTION_LONG: str = "Article long description"


data = CSVData(SUPPLIER_AID='1234-568',
               EAN='EAN number',
               DESCRIPTION_SHORT='Article Name')

for field in asdict(data).values():
    print(field)

Which prints:

1234-568
EAN number
Article Name
Article long description
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.