fix(ros2pkg): replace deprecated importlib.resources.path with files/as_file#1234
fix(ros2pkg): replace deprecated importlib.resources.path with files/as_file#1234darshmenon wants to merge 2 commits into
Conversation
resources.path() is deprecated since Python 3.11 and emits DeprecationWarning on 3.12 (used by ROS 2 Jazzy+). Replace with resources.files().joinpath() + resources.as_file(), which is the recommended API since Python 3.9. Also fixes a latent bug: the old code used template_path after exiting the with-block, so extraction of zip-packaged resources would have produced a stale path. All path-dependent calls are now inside the as_file() context manager.
fujitatomoya
left a comment
There was a problem hiding this comment.
same here, AI usage needs to be disclosed, please use our PR template.
besides, this PR includes unrelated difference from #1233. please include only code and changes related to the PR. do not include unrelated changes.
and DCO is missing.
This doesn't make sense. There's Kilted in between Jazzy and Rolling, and Rolling isn't on Ubuntu 24.04 anymore, it's on 26.04. And this targets Rolling, so I don't see why you'd need to check for regressions on Humble. |
I sourced Jazzy and then ran |
Problem
importlib.resources.path()has been deprecated since Python 3.11 and emitsDeprecationWarningon Python 3.12, which is the interpreter used by ROS 2 Jazzy and Rolling. This means everyros2 pkg createinvocation currently prints a deprecation warning on current Ubuntu 24.04 systems.There is also a latent correctness bug: the existing code exits the
with resources.path(...)context manager before usingtemplate_path, then callsos.path.exists()and_expand_template()on a path that may already be invalid. For resources packaged inside a zip (e.g. installed wheels), the temporary extracted file is deleted when the context manager exits, making the subsequentos.path.exists()check and_expand_template()call operate on a stale path.Fix
Replace
resources.path()withresources.files().joinpath()+resources.as_file(), the API recommended since Python 3.9. Move all path-dependent calls inside theas_file()context manager so the extracted file remains valid for the duration of template expansion.Test Plan
ros2 pkg create --build-type ament_cmake my_pkg— noDeprecationWarningon Python 3.12ros2 pkg create --build-type ament_python my_pkg— all template files generated correctlyros2 pkg create --build-type ament_cmake --node-name my_node my_pkg— node stub created correctly