Robotics StackExchange | Archived questions

Get ROS2 message fields from Python messages?

Can I get the message fields (names and their types) of ROS2 Python messages dynamically like in ROS1 (via __slots__)?

Asked by thinwybk on 2018-09-29 12:26:41 UTC

Comments

Answers

Looking at the latest ROS2 master code, it looks like you can currently get the names of the message fields from __slots__, but not the types:

>>> import std_msgs.msg
>>> x = std_msgs.msg.Header()
>>> dir(x)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_frame_id', '_stamp', 'frame_id', 'stamp']
>>> print(x.__slots__)
['_stamp', '_frame_id']
>>> 

Asked by clalancette on 2018-10-03 13:06:54 UTC

Comments

@thinwybk I'll add that there's no reason for the lack of these methods on the message structures, you should be able to get the field names and types, so we just need to add these methods in the code, see: https://github.com/ros2/rosidl_python/blob/master/rosidl_generator_py/resource/_msg.py.em

Asked by William on 2018-10-05 09:19:47 UTC

Also, they're all properties, so you can look at the properties of the class as well: https://stackoverflow.com/a/1215428/671658 But that still only gives you the names.

Asked by William on 2018-10-05 09:21:28 UTC

@William I would need the field names with their corresponding types. I could not find unit tests for the provided message meta info. From a functional point of view it's not required anyway. Would you accept a PR without tests for it?

Asked by thinwybk on 2018-10-08 02:43:16 UTC

ROS 2 Crystal does have that information: MessageClass.get_fields_and_field_types() (see https://github.com/ros2/rosidl_python/blob/0f5c8f360be92566ad86f4b29f3db1febfca2242/rosidl_generator_py/resource/_msg.py.em#L202-L203)

Note that the API and returned information for this kind of introspection is likely going to change in the next ROS 2 release (Dashing) so check the migration in the future to check for information.

Asked by Dirk Thomas on 2019-02-19 16:20:47 UTC

Comments