From 784339553f8bb2757283c04739156349d3f1d6b1 Mon Sep 17 00:00:00 2001 From: Lanfon Date: Sat, 6 Mar 2021 22:28:11 +0800 Subject: [PATCH 1/2] bpo-43419: fix contextvars behaviors in asyncio REPL --- Lib/asyncio/__main__.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Lib/asyncio/__main__.py b/Lib/asyncio/__main__.py index 18bb87a5bc4ffd..7db47798f8d601 100644 --- a/Lib/asyncio/__main__.py +++ b/Lib/asyncio/__main__.py @@ -7,8 +7,9 @@ import threading import types import warnings +import contextvars -from . import futures +from . import futures, iscoroutinefunction class AsyncIOInteractiveConsole(code.InteractiveConsole): @@ -25,12 +26,17 @@ def runcode(self, code): def callback(): global repl_future global repl_future_interrupted + global repl_context repl_future = None repl_future_interrupted = False func = types.FunctionType(code, self.locals) try: + if not iscoroutinefunction(func): + code_ = self.compile("repl_ctx.run(repl_f)", self.filename) + new_locals = dict(repl_ctx=repl_context, repl_f=func, **self.locals) + func = types.FunctionType(code_, new_locals) coro = func() except SystemExit: raise @@ -52,7 +58,7 @@ def callback(): except BaseException as exc: future.set_exception(exc) - loop.call_soon_threadsafe(callback) + loop.call_soon_threadsafe(callback, context=repl_context.copy()) try: return future.result() @@ -103,6 +109,7 @@ def run(self): repl_future = None repl_future_interrupted = False + repl_context = contextvars.Context() try: import readline # NoQA From 5eedb2b679635234942f54797288adac638ddab7 Mon Sep 17 00:00:00 2001 From: Lanfon Date: Sun, 7 Mar 2021 23:59:47 +0800 Subject: [PATCH 2/2] remove redundant --- Lib/asyncio/__main__.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Lib/asyncio/__main__.py b/Lib/asyncio/__main__.py index 7db47798f8d601..347a08a2962602 100644 --- a/Lib/asyncio/__main__.py +++ b/Lib/asyncio/__main__.py @@ -9,7 +9,7 @@ import warnings import contextvars -from . import futures, iscoroutinefunction +from . import futures class AsyncIOInteractiveConsole(code.InteractiveConsole): @@ -33,10 +33,6 @@ def callback(): func = types.FunctionType(code, self.locals) try: - if not iscoroutinefunction(func): - code_ = self.compile("repl_ctx.run(repl_f)", self.filename) - new_locals = dict(repl_ctx=repl_context, repl_f=func, **self.locals) - func = types.FunctionType(code_, new_locals) coro = func() except SystemExit: raise @@ -58,7 +54,7 @@ def callback(): except BaseException as exc: future.set_exception(exc) - loop.call_soon_threadsafe(callback, context=repl_context.copy()) + loop.call_soon_threadsafe(callback, context=repl_context) try: return future.result()