Topics_quiz: need for clarification

To put my confusion in a simple way: I did not see a clear instruction on calling a publisher inside of a callback function of a subscriber until I see the quiz solution. It seems like the callback func doesn’t need the Twist() variable and the publisher as input arguments to get access to them, which is not very intuitive to me and please provide some reading material here just so I can understand better. Thank you

Hi @zhaoerli,

No, it doesn’t.

It seems your confusion is coming from the use of Python global variables. The rospy.Publisher (pub) and Twist() (move) variables were created as global variables and are therefore accessible within the callback function.

I quite agree that it might not be very intuitive, but that’s “procedural” Python for you! I have a challenge for you: can you try implementing the solution using a Python class? Within a class, pub, sub and move can just be instance variables and the callback can be an instance method. It would be much more intuitive that way.

I hope you find this useful.

Cheers.


PS: Even though the callback was defined at the top of the program, these variables are already available before the subscriber callback is ever called, as it’s only called after rospy.spin().

PPS: The other option is to define your rospy.Publisher and Twist() variables inside the callback, but this would mean recreating them all the time. And this would not be efficient.

PPPS: If you are not familiar with Python, I suggest you take our free Python 3 for Robotics course.