ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Variable namespaces in classes (Python3)

asked 2022-04-11 08:16:06 -0500

WarTurtle gravatar image

I am having difficulties using variable namespaces with python3 classes

Here's a snippet of code that I would think would work, but doesn't.

In the BasicNavigator class:

    self.namespace = ''

    self.localization_pose_sub = self.create_subscription(PoseWithCovarianceStamped,
                                                          self.namespace + '/amcl_pose',
                                                          self._amclPoseCallback,
                                                          amcl_pose_qos)

In main:

navigator = BasicNavigator()

navigator.namespace = "robot1"

This does not work, it does not recognize the "robot1" in the class.

Instead, if I remove the self.namespace and just write the topic name as such: 'robot1/amcl_pose' it works, but I need to be able to have a variable amount of robots...

What am I doing wrong?

edit retag flag offensive close merge delete

Comments

Very likely the subscription is getting created beforeself.namespace is being set to robot1. What if you made the constructor of BasicNavigator take in a namespace, so that you can do something like self.namespace = namespace?

abhishek47 gravatar image abhishek47  ( 2022-04-11 11:31:38 -0500 )edit

As the previous comment said, you need to rearrange when you're setting the namespace and when the subscription is created.

aprotyas gravatar image aprotyas  ( 2022-04-11 14:50:09 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-04-12 07:37:06 -0500

WarTurtle gravatar image

Thanks, abhishek47 and aprotyas for your comments. It worked by creating a method with the namespace argument.

In BasicNavigor class:

def createSubscriptions(self, namespace):
    self.localization_pose_sub = self.create_subscription(PoseWithCovarianceStamped,
                                                          namespace + 'amcl_pose',
                                                          self._amclPoseCallback,
                                                          amcl_pose_qos)

And then I call this in main:

navigator = BasicNavigator()

namespace = "robot1"
navigator.createSubscriptions(namespace)

Not sure if this is exactly what you wanted me to try, but it works, so I'm happy :)

edit flag offensive delete link more

Comments

Something along these lines, yes. Good to know that it worked!

aprotyas gravatar image aprotyas  ( 2022-04-13 00:18:37 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2022-04-11 08:16:06 -0500

Seen: 131 times

Last updated: Apr 12 '22