Search code examples
pythonpython-dataclasses

How do I pull out the attributes or field names from a dataclass?


I have a dataclass, say Car:

from dataclasses import dataclass

@dataclass
class Car:
    make: str
    model: str
    color: hex
    owner: Owner

How do I pull out the attributes or fields of the dataclass in a list?, e.g.

attributes = ['make', 'model', 'color', 'owner']

Solution

  • Use dataclasses.fields to pull out the fields, from the class or an instance. Then use the .name attribute to get the field names.

    >>> from dataclasses import fields
    >>> attributes = [field.name for field in fields(Car)]
    >>> print(attributes)
    ['make', 'model', 'color', 'owner']