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]
A dataclass can very well have regular instance and class methods. Dataclasses were introduced from Python version 3.7. For Python versions below 3.7, it has to be installed as a library.
Use the @dataclass decorator from the dataclasses module to make a class a dataclass. The dataclass object implements the __eq__ and __str__ by default. Use the astuple() and asdict() functions to convert an object of a dataclass to a tuple and dictionary. Use frozen=True to define a class whose objects are immutable.
The __post_init__ method is called just after initialization. In other words, it is called after the object receives values for its fields, such as name , continent , population , and official_lang .
A data class is a class typically containing mainly data, although there aren't really any restrictions. It is created using the new @dataclass decorator, as follows: from dataclasses import dataclass @dataclass class DataClassCard: rank: str suit: str.
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']
You can use the asdict method of the dataclasses
module. For example:
from dataclasses import dataclass, asdict
@dataclass
class Person:
age: int
name: str
adam = Person(25, 'Adam')
# if you want the keys
print(asdict(adam).keys()) # dict_keys(['age', 'name'])
# if you want the values
print(asdict(adam).values()) # dict_values([25, 'Adam'])
Both methods above return a View
object which you can iterate on, or you can convert it to list
using list(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With