Search code examples
pythonmultithreadinggrpcpython-multithreading

Passing a list to a thread


I am trying to launch a thread on python that needs to handle updates from a server.

I am then trying to sends this data above on a service that I have via GRPC, using a bidirectional stream.

So the idea is that when an events arrive the thread will push on the array the new event. In this way, using an iterator, the GRPC service will see that something was pushed in the array and it will stream it on the bidirectional stream.

In order to achieve this goal, I need to pass as argument to the function that will be handled by the new thread an array.

Here it is the code:

thread = Thread(target=handler_subscriptions , args= {address, endpoint , path1 ,event_array})

event_array is the array I need to pass. I get this runtime error:

TypeError: unhashable type: 'list'

Can someone explain me why , and how to bypass the problem?


Solution

  • The args parameter to Thread contains the positional arguments for the target callable. As such, it needs to be an ordered collection. You cannot use a set, because the arguments will be used in no guaranteed order.

    Use a tuple instead:

    thread = Thread(target=handler_subscriptions, args=(address, endpoint, path1, event_array))
    

    although a list would also work.

    The exact cause of the error message that you saw was that one of the elements of your attempted set was not of a hashable type. This is fortuitous, in that it raised an exception that caused you to address this issue (because elements of a set must be hashable), but changing it to a hashable type would not be the solution here, although it might happen to work some of the time if by chance the elements of the set come out in insertion order.