Skip to content
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
9 changes: 7 additions & 2 deletions bpython/curtsiesfrontend/coderunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"""

import code
import contextvars
import logging
import signal

Expand Down Expand Up @@ -92,6 +93,7 @@ def __init__(self, interp=None, request_refresh=lambda: None):
code asks for a refresh - to, for example, update the screen.
"""
self.interp = interp or code.InteractiveInterpreter()
self.context = contextvars.copy_context()
self.source = None
self.main_context = greenlet.getcurrent()
self.code_context = None
Expand Down Expand Up @@ -129,7 +131,7 @@ def run_code(self, for_code=None):
"""
if self.code_context is None:
assert self.source is not None
self.code_context = greenlet.greenlet(self._blocking_run_code)
self.code_context = greenlet.greenlet(self._run_code_in_context)
if is_main_thread():
self.orig_sigint_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, self.sigint_handler)
Expand Down Expand Up @@ -187,6 +189,9 @@ def _blocking_run_code(self):
return SystemExitRequest(*e.args)
return Unfinished() if unfinished else Done()

def _run_code_in_context(self):
return self.context.run(self._blocking_run_code)

def request_from_main_context(self, force_refresh=False):
"""Return the argument passed in to .run_code(for_code)

Expand Down Expand Up @@ -236,4 +241,4 @@ def isatty(self):

@property
def encoding(self):
return self._real_fileobj.encoding
return self._real_fileobj.encoding
18 changes: 17 additions & 1 deletion bpython/test/test_curtsies_coderunner.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import code
import sys
import unittest
from unittest import mock

from bpython.curtsiesfrontend.coderunner import CodeRunner, FakeOutput
from bpython.curtsiesfrontend.coderunner import CodeRunner, Done, FakeOutput


class TestCodeRunner(unittest.TestCase):
Expand Down Expand Up @@ -44,6 +45,21 @@ def ctrlc():
c.load_code("1 + 1")
c.run_code()

def test_context_is_preserved_between_commands(self):
interp = code.InteractiveInterpreter(locals={})
c = CodeRunner(interp=interp)

c.load_code("import decimal")
self.assertIsInstance(c.run_code(), Done)

c.load_code("decimal.getcontext().rounding = decimal.ROUND_HALF_UP")
c.run_code()

c.load_code("rounding = decimal.getcontext().rounding")
c.run_code()

self.assertEqual(interp.locals["rounding"], "ROUND_HALF_UP")


class TestFakeOutput(unittest.TestCase):
def assert_unicode(self, s):
Expand Down
Loading