sam
sam

Reputation: 21

Run async task in class that extends Threading - python

I've created a python class that extends threading and uses a library that runs asyncio tasks.

import threading
from app.food import recipes

class Mixer(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    
    async def run(self):
        while True:
           ingredients = await recipes.get()
   

When I run the code I get following error:

RuntimeWarning: coroutine 'Mixer.run' was never awaited

Any ideas how to solve it?

Thanks

Upvotes: 0

Views: 359

Answers (1)

chrslg
chrslg

Reputation: 13316

run in Thread class is not supposed to be a coroutine. It is just called as is. Not waited for. It is called obj.run() not by a await obj.run() nor asyncio.run(self.run) or whatever.

When you extend a class, you are supposed to overload methods while keeping the same interface (that's the whole point of extending/overloading). Here, you are not. Your are replacing a method that is meant to be just ran, by a one that is supposed to be awaited.

What exactly are you trying to do? There are already, in asyncio, some functions to transform a (implicit) thread into a coroutine (for non-asyncio blocking tasks, that you want to "await"). See to_thread() method, for example. Or other functions to interact with threads. Depending on what you are really trying to do here.

Upvotes: 1

Related Questions