Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a simple list of a dataclass field

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]
like image 394
Sylvain Page Avatar asked Nov 04 '19 12:11

Sylvain Page


People also ask

Can Dataclass have methods?

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.

How do you define a Dataclass in Python?

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.

What is __ Post_init __?

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 .

What is @dataclass?

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.


Video Answer


2 Answers

The answer depends on whether or not you have access to an object of the class.

Just using 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)]

From an existing object

If you have a constructed object of the class, then you have two additional options:

  1. Use dataclasses.fields on the object:
[field.name for field in dataclasses.fields(obj)]
  1. Use 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 

Full example

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']
like image 97
teichert Avatar answered Oct 03 '22 17:10

teichert


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(...).

like image 26
adnanmuttaleb Avatar answered Oct 03 '22 16:10

adnanmuttaleb