Using callback_args in Subscriber

Hi,

I want to send some arguments into a callback function of Subscriber.
I tried. I can do it if I send a tuple of arguments. Could I send arguments without using a tuple or a list?

It works:
sub = rospy.Subscriber(
‘/kobuki/laser/scan’,
LaserScan,
callback,
callback_args=(pub, twist),
)

Hi @NguyenDuyDuc ,

No, you cannot. Arguments of a function are serialized data handled within the program’s compiler or the interpreter. Therefore you can pass the arguments as a serialized data or as an iterable item - like list or tuple or array - but not as separate variables.

What do you wish to do? Why are you trying to do something that is not usually done in programming?
What do you want to accomplish? If you can explain those questions, perhaps we can provide you with better/suitable solutions.

Regards,
Girish

I want to have a callback function like:

def callback(msg, arg1, arg2, arg3):

so in callback function, I just call the arg1, …

Instead of:

def callback(msg, args):
arg1 = args[0]
arg2 = args[1]

Because I think if I have10 args, It will take ten lines to unpack. So I wonder if there is any way to make it better?

You can unpack your callback variables in one line. It’s called “destructuring” (Google it for more information).

For this specific example, you could do:

arg1, arg2 = args                # if there are only 2 args
arg1, arg2, ..., arg10 = args    # if there are 10 args
arg1, arg2, *other_args = args   # if they are more than two and you only need the first 2

You should have an idea of the number and order of arguments in advance.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.