[New-bugs-announce] [issue41733] ContextVar get value is unexpected

Jason Chen report at bugs.python.org
Sun Sep 6 09:41:11 EDT 2020


New submission from Jason Chen <chenzep at gmail.com>:

import asyncio
from contextvars import *

var = ContextVar('VarTest', default=None)

def get_var(tag=None):
    obj = var.get()
    if obj is None:
        obj = object()
        var.set(obj)
    print(f'{tag=}: get_var result is {obj=}')
    return obj

async def get_var_object(tag):
    return get_var(tag)

async def asyncio_main():
    await asyncio.gather(*[get_var_object(id) for id in range(2)])

def test(get_var_before_run=False):
    print(f'{get_var_before_run=}')
    if get_var_before_run:
        get_var()
    asyncio.run(asyncio_main())
    print()


if __name__ == '__main__':
    test(get_var_before_run=False)
    test(get_var_before_run=True)


---- Output:-------

tag=0: get_var result is obj=<object object at 0x7f194571d210>
tag=1: get_var result is obj=<object object at 0x7f194571d200>

get_var_before_run=True
tag=None: get_var result is obj=<object object at 0x7f194571d210>
tag=0: get_var result is obj=<object object at 0x7f194571d210>
tag=1: get_var result is obj=<object object at 0x7f194571d210>


--- my question: ------
-- all objects in get_var_before_run=True are same.
-- my expected result is all objects should be different, because the code runs in different context.

----------
components: asyncio
messages: 376464
nosy: asvetlov, chenzep, yselivanov
priority: normal
severity: normal
status: open
title: ContextVar get value is unexpected
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41733>
_______________________________________


More information about the New-bugs-announce mailing list