diff --git a/README.md b/README.md index 398cbb9..222a688 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Reloading the extension will remove all spaces. ```python %%space alpha = 0.50 -print(alpha) +alpha ``` When you execute a cell within a space, all references are firstly searched in @@ -51,33 +51,6 @@ execution equivalent to not using such keyword. Mutable objects in the user namespace can be altered (e.g. appending an item to a list). -#### Console output - -Conversely to the standard usage of the Python console, you need to print -objects explicitly (e.g. by using `print`). - -- No output to console - ```python - %%space - 100 - ``` -- Output to console - ```python - %%space - print(100) - ``` - -If you want IPython to use more advanced representations, you can do so via -IPython's display library (e.g. display a Pandas dataframe as a HTML table). - -```python -%%space -from IPython.display import display -from pandas import DataFrame -dataframe = DataFrame(data=[[1, 2]]) -display(dataframe) -``` - ### Remove a space ```python diff --git a/jupyter_spaces/space.py b/jupyter_spaces/space.py index 476a7a0..7c3b89e 100644 --- a/jupyter_spaces/space.py +++ b/jupyter_spaces/space.py @@ -1,3 +1,6 @@ +import ast +import sys + from jupyter_spaces.errors import RegistryError @@ -101,7 +104,16 @@ def execute(self, source): Args: source (str): Source code. """ - exec(source, self._execution_namespace) + tree = ast.parse(source=source) + + interactive_tree = ast.Interactive(body=tree.body) + if sys.version_info > (3, 8): + interactive_tree.type_ignores = tree.type_ignores + + compiled_interactive_tree = compile( + source=interactive_tree, filename="", mode="single" + ) + exec(compiled_interactive_tree, self._execution_namespace) class ExecutionNamespace(dict): diff --git a/tests/test_magics.py b/tests/test_magics.py index e24cc1b..22da064 100644 --- a/tests/test_magics.py +++ b/tests/test_magics.py @@ -152,6 +152,11 @@ def test_get_spaces_reflects_extension_reload(ip): assert not ip.user_global_ns["spaces"] +def test_space_outputs_to_console(ip, capsys): + ip.run_cell_magic(magic_name="space", line="tomato", cell="100") + assert capsys.readouterr().out == "100\n" + + def test_space_can_print_to_console(ip): with capture_output() as captured: ip.run_cell_magic(magic_name="space", line="tomato", cell="print(100)")