Skyscanner / aiotask-context

Contextual information for asyncio tasks
MIT License
161 stars 25 forks source link

Context is global for all the parallel coroutines running #11

Closed apollovy closed 7 years ago

apollovy commented 7 years ago

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.

apollovy commented 7 years ago

Oops, I see my error, sorry for disturbing 😁