Reputation: 9826
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']
Upvotes: 4
Views: 5356
Reputation: 9826
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']
Upvotes: 8