From 547245a3fb7526662fbce9b0caffd7980d9d2791 Mon Sep 17 00:00:00 2001 From: Chris Lalancette Date: Fri, 31 May 2024 16:56:12 -0400 Subject: [PATCH] Make publishers context-manager aware. (#1289) The main reason to do this is so that we can change example code to use context managers for managing the lifetimes of publishers (and other entities), which should make the code significantly easier to read. Signed-off-by: Chris Lalancette --- rclpy/rclpy/publisher.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/rclpy/rclpy/publisher.py b/rclpy/rclpy/publisher.py index d1a14ee7e..998e555d9 100644 --- a/rclpy/rclpy/publisher.py +++ b/rclpy/rclpy/publisher.py @@ -12,7 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Generic, List, Type, TypeVar, Union +from types import TracebackType +from typing import Generic, List, Optional, Type, TypeVar, Union from rclpy.callback_groups import CallbackGroup from rclpy.duration import Duration @@ -128,3 +129,14 @@ def wait_for_all_acked(self, timeout: Duration = Duration(seconds=-1)) -> bool: """ with self.handle: return self.__publisher.wait_for_all_acked(timeout._duration_handle) + + def __enter__(self) -> 'Publisher': + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self.destroy()