Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 599
Amin Shah Gilani Avatar asked Sep 05 '25 16:09

Amin Shah Gilani


1 Answers

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']
like image 153
Amin Shah Gilani Avatar answered Sep 07 '25 16:09

Amin Shah Gilani