ros2 / rclpy

rclpy (ROS Client Library for Python)
Apache License 2.0
272 stars 221 forks source link

Make rclpy.context.Context be a context manager #1106

Open felixdivo opened 1 year ago

felixdivo commented 1 year ago

Feature request

Feature description

rclpy.context.Context would be useful to have as a context manager. This would allow for:

with Context() as context:
    executor = MultiThreadedExecutor(context=context)
    do_something_cool(executor)

Instead of

context = Context()
try:
    context.init()
    executor = MultiThreadedExecutor(context=context)
    do_something_cool(executor)
finally:
    context.try_shutdown()

The first approach is shorter and (for some) conceptually easier. In both cases context can be referenced afterwards although it is invalid. However, in the first case it is much more clear that any sane use is within the with context: ... construct. And, one cannot forget to close it in the end. It is arguably more Pythonic.

Implementation considerations

One could use shutdown or try_shutdown at the end of the context block. The latter makes more sense, since it allows for more complex scenarios where the context is already in some of the cases.

clalancette commented 1 year ago

This is a good idea, thanks. We probably aren't going to work on this, but we would definitely review pull requests that implemented it.

felixdivo commented 1 year ago

Okay nice. Is wrapping around context.init()/context.try_shutdown() even the right thing to do? Then maybe I can have a look. 😄

mjcarroll commented 1 year ago

Yep, I think it maps the ROS concept cleanly into a more pythonic pattern. Happy to take a look if you open a PR.

felixdivo commented 1 year ago

There is also #1118, for rclpy.executor.Executor