Python how to initialize thread with unknown number of arguments?
-
19-06-2021 - |
Pregunta
I'm having trouble using the starred expressions in combination with fixed argument lists when attempting to create threads.
Consider the following code:
the_queue = Queue()
def do_something(arg1, arg2, queue):
# Do some stuff...
result = arg1 + arg2
queue.put(result)
def init_thread(*arguments):
t = Thread(target=do_something, args=(arguments, the_queue))
t.start()
t.join()
init_thread(3,6)
This throws the exception:
TypeError: do_something() takes exactly 3 arguments (2 given)
In other words, the "arguments" tuple is evaluated as one tuple object (i.e. it's not unpacked), and the_queue is regarded as the second argument.
The code needs to be able to initalize threads calling different methods with an unknown number of arguments, but that always will have a "queue" parameter at the end.
Is there any way to achieve this? In that case, how? And if not -- what am I doing wrong?
Thanks.
EDIT: I should add that calling the "init_thread()" method with the queue as an argument is not an option, since I don't want the rest of my code to be "aware" of how the thread handler works internally...
Solución
You need to make a new tuple
.
t = Thread(target = do_something, args = arguments + (the_queue, ))
Otros consejos
You can also unpack the packed-up *arguments tuple, like so:
>>> def Print(*args):
... print('I am prepended to every message!', *args)
...
>>> Print('This', 'has', 'four', 'arguments')
I am prepended to every message! This has four arguments
>>> def Print(*args):
... print('I am prepended to every message!', args)
...
>>> Print('This', 'has', 'four', 'arguments')
I am prepended to every message! ('This', 'has', 'four', 'arguments')
So you see, referring to *agruments, as opposed to arguments, will unpack the tuple. Thus your code might be:
def init_thread(*arguments):
t = Thread(target=do_something, args=(*arguments, the_queue))
t.start()
t.join()