pythonc#python-3.xasynchronous

Does python have something similar to C#'s AsyncLocal?


I guess this is a one-liner question: with C# you can use AsyncLocal to store some ambient data that is local to a given asynchronous control flow, but what would I use in python to get a similar functionality?


Solution

  • I think You can achieve similar functionality to C#'s AsyncLocal by using contextvars.ContextVar. This allows you to store and manage text-local state in tasks or asynchronous programs without leaking it to other parts of the code. ContextVar ensures that each asynchronous control stream has its own version of the data, just like AsyncLocal in C#.

    import contextvars
    
    my_var = contextvars.ContextVar('my_var')
    
    my_var.set('value1')
    
    print(my_var.get())
    async def task():
        my_var.set('value2')
        print(my_var.get())