Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "normal-palace",
"metadata": {},
"outputs": [],
"source": [
"import contextvars, asyncio\n",
"VAR = contextvars.ContextVar(\"VAR\", default=\"default\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "boxed-opportunity",
"metadata": {},
"outputs": [],
"source": [
"async def produce_result(x):\n",
" return x\n",
"\n",
"async def read_var():\n",
" print(\"Var:\", VAR.get())"
]
},
{
"cell_type": "markdown",
"id": "lesbian-signature",
"metadata": {},
"source": [
"## The following is broken"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "comic-gambling",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<Token var=<ContextVar name='VAR' default='default' at 0x7fb04c42e1d0> at 0x7fb04c498dc0>"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"result = await produce_result(\"bug fixed yayy\")\n",
"VAR.set(result)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "minimal-milwaukee",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Var: default\n"
]
}
],
"source": [
"await read_var()"
]
},
{
"cell_type": "markdown",
"id": "arranged-monitoring",
"metadata": {},
"source": [
"## The following works"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "upset-portugal",
"metadata": {},
"outputs": [],
"source": [
"result = await produce_result(\"this worked before\")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "virtual-calendar",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<Token var=<ContextVar name='VAR' default='default' at 0x7fb04c42e1d0> at 0x7fb04c4980c0>"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"VAR.set(result)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "collected-leave",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Var: this worked before\n"
]
}
],
"source": [
"await read_var()"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "regular-cursor",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6.2.0\n"
]
}
],
"source": [
"import ipykernel\n",
"print(ipykernel.__version__)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Default (Python 3.8)",
"language": "python",
"name": "default_python3.8"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment