From ffcdae92d450cc54ef29ea8b7fa7a3467dce4416 Mon Sep 17 00:00:00 2001 From: Chris Lalancette Date: Mon, 3 Jun 2024 09:11:17 -0400 Subject: [PATCH] Make subscriptions context-manager aware. (#1291) Signed-off-by: Chris Lalancette --- rclpy/rclpy/subscription.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/rclpy/rclpy/subscription.py b/rclpy/rclpy/subscription.py index 31eecdd67..131da3d30 100644 --- a/rclpy/rclpy/subscription.py +++ b/rclpy/rclpy/subscription.py @@ -15,7 +15,8 @@ from enum import Enum import inspect -from typing import Callable, Generic, List, Type, TypeVar +from types import TracebackType +from typing import Callable, Generic, List, Optional, Type, TypeVar from rclpy.callback_groups import CallbackGroup from rclpy.event_handler import EventHandler, SubscriptionEventCallbacks @@ -123,3 +124,14 @@ def callback(self, value: Callable[[MsgT], None]) -> None: raise RuntimeError( 'Subscription.__init__(): callback should be either be callable with one argument' '(to get only the message) or two (to get message and message info)') + + def __enter__(self) -> 'Subscription': + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self.destroy()