From 182c5187a07580c43db85aea8bc594a74d8ddc4b Mon Sep 17 00:00:00 2001 From: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Date: Sun, 22 Mar 2026 01:33:01 +0800 Subject: [PATCH] refactor: simplify _extract_namespaced_type_fields, remove redundant try-except and post-processing Made-with: Cursor --- msgcenterpy/instances/ros2_instance.py | 45 +++++++++++--------------- 1 file changed, 18 insertions(+), 27 deletions(-) diff --git a/msgcenterpy/instances/ros2_instance.py b/msgcenterpy/instances/ros2_instance.py index 064d0e3..29d58bf 100644 --- a/msgcenterpy/instances/ros2_instance.py +++ b/msgcenterpy/instances/ros2_instance.py @@ -1,11 +1,8 @@ import array import importlib -import logging from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Optional, Type -logger = logging.getLogger(__name__) - from rosidl_parser.definition import NamespacedType # type: ignore from rosidl_runtime_py import ( # type: ignore import_message_from_namespaced_type, @@ -248,29 +245,23 @@ class ROS2MessageInstance(MessageInstance[Any]): type_info: 要填充 object_fields 的 TypeInfo 对象 namespaced_type: rosidl NamespacedType 定义 """ - from msgcenterpy.core.type_info import TypeInfoPostProcessor + msg_cls = import_message_from_namespaced_type(namespaced_type) + msg_instance = msg_cls() - try: - msg_cls = import_message_from_namespaced_type(namespaced_type) - msg_instance = msg_cls() + # noinspection PyProtectedMember + slots = msg_instance._fields_and_field_types + slot_types = msg_instance.SLOT_TYPES - # noinspection PyProtectedMember - slots = msg_instance._fields_and_field_types - slot_types = msg_instance.SLOT_TYPES - - for field_name, slot_type in zip(slots, slot_types): - std_type = TypeConverter.rosidl_definition_to_standard(slot_type) - python_type = TypeConverter.standard_to_python_type(std_type) - field_type_info = TypeInfo( - field_name=field_name, - field_path=f"{type_info.field_path}.{field_name}", - standard_type=std_type, - python_type=python_type, - original_type=slot_type, - ) - self._extract_from_rosidl_definition(field_type_info) - TypeInfoPostProcessor.post_process_type_info(field_type_info) - field_type_info.add_constraint(ConstraintType.REQUIRED, True) - type_info.object_fields[field_name] = field_type_info - except Exception as e: - logger.warning("Failed to extract fields from NamespacedType %s: %s", namespaced_type, e) + for field_name, slot_type in zip(slots, slot_types): + std_type = TypeConverter.rosidl_definition_to_standard(slot_type) + python_type = TypeConverter.standard_to_python_type(std_type) + field_type_info = TypeInfo( + field_name=field_name, + field_path=f"{type_info.field_path}.{field_name}", + standard_type=std_type, + python_type=python_type, + original_type=slot_type, + ) + self._extract_from_rosidl_definition(field_type_info) + field_type_info.add_constraint(ConstraintType.REQUIRED, True) + type_info.object_fields[field_name] = field_type_info