Search code examples
pythonpython-dataclasses

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,t]

Solution

  • 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']