Issue
How can I create dummy Task object that will be immediately done?
Why?
I often check if task is not None and task.done()
just to check if another task can be spawn and feel it's a boilerplate that can be avoided:
def __init__(self):
self._do_something_task: Optional[asyncio.Task] = None
async def _do_something(self):
await asyncio.sleep(10)
# something
def trigger_do_something(self):
if self._do_something_task is not None and self._do_something_task.done():
asyncio.create_task(self._do_something())
Currently my workaround is:
def __init__(self):
self._do_something_task: asyncio.Task = asyncio.create_task(asyncio.sleep(0))
async def _do_something(self):
await asyncio.sleep(10)
# something
def trigger_do_something(self):
if self._do_something_task.done():
asyncio.create_task(self._do_something())
but I feel its not very readable at the first glance.
Solution
Python is a language with duck typing, so as long as some object can answer if it's done()
, it should do the job:
class DummyTask:
def done(self):
return True
print(DummyTask().done()) # True
More smart way to do it is to use mock library.
Answered By - Mikhail Gerasimov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.