Python type checking in ROS2?

Hello everyone,

I have recently started to work on some small, some big Python projects that make use of the ROS client libraries (e.g. rclpy, launch, …). When I opened the files I was very excited to see that type annotations had been added to them! However, I quickly realized that it is very hard to properly typecheck a Python package in the current state of things:

  • Most packages do not export a py.typed file, so mypy interprets them as untyped
  • A lot of those type annotations are not checked in CI, so they contain errors
  • Generated messages do not contain type annotations

A number of projects, PRs and issues have been created to work around these issues:

Unfortunately, most of those haven’t seen very much follow-up. I would personally love to improve this situation, but I wanted to get some more opinions from the community.

I am also saddened to see that the quality guide does not make a single mention to Python. Since some critical parts of the ROS2 ecosystem (notably launch system) are written in Python, I think it’s a regrettable omission.

Cheers,
Hervé

7 Likes

I don’t have an informed opinion on this, but I’d imagine that adding typing to the autogenerated messages would be relatively straightforward.

Yes! Actually, a project exists that does just that: generate type stubs from messages. Ideally it would be added to rosidl_python itself, but as I mentioned above, the issue doesn’t seem to gain much traction…

2 Likes

Agreeing that typing with rclpy is pretty dismal and ignored, just like the documentation, but a pretty great solution is to use dynamic typechecking with beartype (gh). You just tag classes or free-floating functions with @beartype, and that’s it. I combine it with mypy checking, but mypy isn’t always able to pull through, like so.