Skip to content

Conversation

@Arfey
Copy link
Contributor

@Arfey Arfey commented Nov 10, 2025

This pull request enhances the sync_to_async utility in asgiref/sync.py by allowing users to pass a custom contextvars.Context. This provides finer control over context variable propagation when running synchronous code in asynchronous environments. Comprehensive tests have been added to ensure correct behavior, especially regarding context isolation and parallel task execution.

More details https://code.djangoproject.com/ticket/36714#comment:17

@Arfey Arfey force-pushed the feat/added-custom-context-parameter-for-sync-to-async branch from 89f62d0 to 23f9635 Compare November 10, 2025 23:39


@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info < (3, 11), reason="requires python3.11")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TypeError: create_task() got an unexpected keyword argument 'context'

finally:
_restore_context(context)
if self.context is None:
_restore_context(context)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to keep the default behavior

import asyncio
import contextvars

value = contextvars.ContextVar('value')

async def main():
    value.set(0)
    
    async def inner():
        value.set(value.get() + 1)
    
    context = contextvars.copy_context()
    
    await asyncio.gather(
        asyncio.create_task(inner(), context=context),
        asyncio.create_task(inner(), context=context),
        asyncio.create_task(inner(), context=context),
    )
    
    assert context.get(value) == 3
    assert value.get() == 0
    
    print("Done")


asyncio.run(main())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant