Convert Topic Message to Dictionary in Python Callback

I would like to save a topic message into a file in a Python callback. I can use a csv.DictWriter if I first convert the message into a dictionary. Is there a better way of converting a message into a dictionary rather than iterating over msg._fields_and_field_types? I cannot use vars() since the message does not have a dict attribute. Is it safe to rely on _fields_and_field_types in future ROS distributions? Thanks!

def _callback(self, msg):
    msg_dict = {field: getattr(msg, field) for field in msg._fields_and_field_types if hasattr(msg, field)}

Thanks for your question. However we ask that you please ask questions on following our support guidelines:

ROS Discourse is for news and general interest discussions. ROS Answers provides a Q&A site which can be filtered by tags to make sure the relevant people can find and/or answer the question, and not overload everyone with hundreds of posts.