Skip to content

Commit

Permalink
Make service servers context-manager aware. (#1294)
Browse files Browse the repository at this point in the history
This way it is much easier to create examples that properly
clean up after themselves.

Signed-off-by: Chris Lalancette <[email protected]>
  • Loading branch information
clalancette authored Jun 4, 2024
1 parent 793e3a2 commit b49ceff
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
14 changes: 14 additions & 0 deletions rclpy/rclpy/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from types import TracebackType
from typing import Callable
from typing import Optional
from typing import Type
from typing import TypeVar

from rclpy.callback_groups import CallbackGroup
Expand Down Expand Up @@ -115,3 +118,14 @@ def destroy(self):
should call :meth:`.Node.destroy_service`.
"""
self.__service.destroy_when_not_in_use()

def __enter__(self) -> 'Service':
return self

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.destroy()
7 changes: 7 additions & 0 deletions rclpy/test/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,10 @@ def test_get_service_name_after_remapping(service_name, namespace, cli_args, exp

srv.destroy()
node.destroy_node()


def test_service_context_manager():
with rclpy.create_node('ctx_mgr_test') as node:
with node.create_service(
srv_type=Empty, srv_name='empty_service', callback=lambda _: None) as srv:
assert srv.service_name == '/empty_service'

0 comments on commit b49ceff

Please sign in to comment.