python contextvars 用法

nxdong October 09, 2022 [python] #contextvars

python里contextvars保存上下文。

代码

import contextvars

g_var: contextvars.ContextVar[int] = contextvars.ContextVar(
    'var', default=42)

g_var1: contextvars.ContextVar[int] = contextvars.ContextVar(
    'var1')


def read_context():
    print("read_context g_var value: {} g_var1 value: {}".format(
        g_var.get(), g_var1.get()))


if __name__ == '__main__':
    g_var1.set("abc")
    default_g_var = g_var.get()
    print("default g_var:", default_g_var)
    g_var.set(22)
    ctx_a = contextvars.copy_context()
    print("ctx_a items:", list(ctx_a.items()))
    ctx_a.run(read_context)

    g_var.set(33)
    ctx_b = contextvars.copy_context()
    print("ctx_a items:", list(ctx_a.items()))
    print("ctx_b items:", list(ctx_b.items()))
    ctx_b.run(read_context)

    read_context()

输出:

default g_var: 42
ctx_a items: [(<ContextVar name='var' default=42 at 0x7f2b58e55800>, 22), (<ContextVar name='var1' at 0x7f2b58ecab60>, 'abc')]
read_context g_var value: 22 g_var1 value: abc
ctx_a items: [(<ContextVar name='var' default=42 at 0x7f2b58e55800>, 22), (<ContextVar name='var1' at 0x7f2b58ecab60>, 'abc')]
ctx_b items: [(<ContextVar name='var' default=42 at 0x7f2b58e55800>, 33), (<ContextVar name='var1' at 0x7f2b58ecab60>, 'abc')]
read_context g_var value: 33 g_var1 value: abc
read_context g_var value: 33 g_var1 value: abc

用于保存异步环境中的上下文。 比如客户端ip啥的。

参考

contextvars