Skip to content

[3.12] gh-124594: Create and reuse the same context for the entire asyncio REPL session (GH-124595) #124849

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Lib/asyncio/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import asyncio
import code
import concurrent.futures
import contextvars
import inspect
import sys
import threading
Expand All @@ -17,6 +18,7 @@ def __init__(self, locals, loop):
super().__init__(locals)
self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
self.loop = loop
self.context = contextvars.copy_context()

def runcode(self, code):
future = concurrent.futures.Future()
Expand Down Expand Up @@ -46,12 +48,12 @@ def callback():
return

try:
repl_future = self.loop.create_task(coro)
repl_future = self.loop.create_task(coro, context=self.context)
futures._chain_future(repl_future, future)
except BaseException as exc:
future.set_exception(exc)

loop.call_soon_threadsafe(callback)
loop.call_soon_threadsafe(callback, context=self.context)

try:
return future.result()
Expand Down
37 changes: 37 additions & 0 deletions Lib/test/test_repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,5 +146,42 @@ def f():
self.assertEqual(traceback_lines, expected_lines)


class TestAsyncioREPLContextVars(unittest.TestCase):
def test_toplevel_contextvars_sync(self):
user_input = dedent("""\
from contextvars import ContextVar
var = ContextVar("var", default="failed")
var.set("ok")
""")
p = spawn_repl("-m", "asyncio")
p.stdin.write(user_input)
user_input2 = dedent("""
print(f"toplevel contextvar test: {var.get()}")
""")
p.stdin.write(user_input2)
output = kill_python(p)
self.assertEqual(p.returncode, 0)
expected = "toplevel contextvar test: ok"
self.assertIn(expected, output, expected)

def test_toplevel_contextvars_async(self):
user_input = dedent("""\
from contextvars import ContextVar
var = ContextVar('var', default='failed')
""")
p = spawn_repl("-m", "asyncio")
p.stdin.write(user_input+"\n")
user_input2 = "async def set_var(): var.set('ok')\n"
p.stdin.write(user_input2+"\n")
user_input3 = "await set_var()\n"
p.stdin.write(user_input3+"\n")
user_input4 = "print(f'toplevel contextvar test: {var.get()}')\n"
p.stdin.write(user_input4+"\n")
output = kill_python(p)
self.assertEqual(p.returncode, 0)
expected = "toplevel contextvar test: ok"
self.assertIn(expected, output, expected)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
All :mod:`asyncio` REPL prompts run in the same :class:`context <contextvars.Context>`. Contributed by Bartosz Sławecki.
Loading