Python get the name of all fields in a dataclass

I am trying to write a function to log dataclasses I would like to get the name of all fields in the dataclass and print the value to each (similar to how you might write a function to print a dictionary)


class Test:
    a: str = "a value"
    b: str = "b value"

test = Test()
def print_data_class(dataclass_instance):
   fields = # get dataclass fileds
   for field in fields:
       print(f{field}: {dataclass.field})

"a"  : "a value"
"b"  : "b value"

However I haven’t been able to find how to get the fields of a dataclass, does anyone know how this could be done?


>Solution :

use the __dict__ property

def print_data_class(dataclass_instance):
   fields = [(attribute, value) for attribute, value in my_instance.__dict__.items()]
   for field in fields:
       print(f{field[0]}: {dataclass.field[0]})

Leave a Reply