This way if multiple concurrent web requests will set it, after setting they all will have same value on getting. I bet that the desired behavior is to share context between tasks in one 'thread', not all the tasks in the loop. Because the latter is not much better than just module-level global dict.
import asyncio
import aiotask_context as context
async def uno():
context.set('x', 2)
await asyncio.sleep(0.001)
return context.get('x')
async def dos():
context.set('x', 1)
await asyncio.sleep(0.001)
return context.get('x')
def test_results_are_various():
loop = asyncio.get_event_loop()
loop.set_task_factory(context.task_factory) # This is the relevant line
results = loop.run_until_complete(asyncio.gather(uno(), dos()))
assert results[0] != results[1]
In this test ioloop will surely switch context between coros, because the io-like operation is present.
This way if multiple concurrent web requests will set it, after setting they all will have same value on getting. I bet that the desired behavior is to share context between tasks in one 'thread', not all the tasks in the loop. Because the latter is not much better than just module-level global dict.
In this test ioloop will surely switch context between coros, because the io-like operation is present.