Can I have easily a list of field from a dataclass
?
@dataclass
class C:
x: int
y: int
z: int
t: int
expected result:
[x,y,z,t]
The answer depends on whether or not you have access to an object of the class.
If you only have access to the class, then you can use dataclasses.fields(C)
which returns a list of field objects (each of which has a .name
property):
[field.name for field in dataclasses.fields(C)]
If you have a constructed object of the class, then you have two additional options:
dataclasses.fields
on the object:[field.name for field in dataclasses.fields(obj)]
dataclasses.asdict(obj)
(as pointed out by this answer) which returns a dictionary from field name to field value. It sounds like you are only interested in the .keys()
of the dictionary:dataclasses.asdict(obj).keys() # gives a dict_keys object
list(dataclasses.asdict(obj).keys()) # gives a list
list(dataclasses.asdict(obj)) # same
Here are all of the options using your example:
from dataclasses import dataclass, fields, asdict
@dataclass
class C:
x: int
y: int
z: int
t: int
# from the class
print([field.name for field in fields(C)])
# using an object
obj = C(1, 2, 3, 4)
print([field.name for field in fields(obj)])
print(asdict(obj).keys())
print(list(asdict(obj).keys()))
print(list(asdict(obj)))
Output:
['x', 'y', 'z', 't']
['x', 'y', 'z', 't']
dict_keys(['x', 'y', 'z', 't'])
['x', 'y', 'z', 't']
['x', 'y', 'z', 't']