rclcpp.exceptions.ParameterAlreadyDeclaredException: parameter 'my_param' has already been declared
ID: ros2/parameter-declare-not-allowed-during-callback
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| ROS2 Humble Hawksbill | active | — | — | — |
| ROS2 Iron Irwini | active | — | — | — |
| ROS2 Jazzy Jalisco | active | — | — | — |
Root Cause
A node attempts to declare a parameter that was already declared, often due to calling `declare_parameter` twice in the same node, or because the parameter was automatically declared by a parent class (e.g., `use_sim_time`).
generic中文
节点尝试声明一个已经声明过的参数,通常是由于在同一个节点中两次调用 `declare_parameter`,或者因为该参数已被父类自动声明(例如 `use_sim_time`)。
Official Documentation
https://docs.ros.org/en/humble/Tutorials/Intermediate/Parameters/Understanding-ROS2-Parameters.htmlWorkarounds
-
95% success Check if the parameter already exists before declaring, using `has_parameter` in C++ or Python. This is especially important when inheriting from nodes that declare common parameters like 'use_sim_time'.
Check if the parameter already exists before declaring, using `has_parameter` in C++ or Python. This is especially important when inheriting from nodes that declare common parameters like 'use_sim_time'.
-
90% success If the parameter is declared by a parent class (e.g., from `rclcpp::Node`), avoid redeclaring it. Instead, set its value via the node options or parameter overrides.
If the parameter is declared by a parent class (e.g., from `rclcpp::Node`), avoid redeclaring it. Instead, set its value via the node options or parameter overrides.
中文步骤
Check if the parameter already exists before declaring, using `has_parameter` in C++ or Python. This is especially important when inheriting from nodes that declare common parameters like 'use_sim_time'.
If the parameter is declared by a parent class (e.g., from `rclcpp::Node`), avoid redeclaring it. Instead, set its value via the node options or parameter overrides.
Dead Ends
Common approaches that don't work:
-
50% fail
Wrapping the declare_parameter call in a try-except block to ignore the exception may cause the parameter to have an unintended default value, leading to subtle bugs.
-
60% fail
Changing the parameter name to a different string (e.g., 'my_param_2') avoids the error but doesn't fix the duplicate declaration; it may also break other code expecting the original name.