Skip to content
Closed
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
24 changes: 3 additions & 21 deletions IPython/core/compilerop.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,31 +91,13 @@ def __init__(self):
# (otherwise we'd lose our tracebacks).
linecache.checkcache = check_linecache_ipython


def _fix_module_ds(self, module):
"""
Starting in python 3.7 the AST for mule have changed, and if
the first expressions encountered is a string it is attached to the
`docstring` attribute of the `Module` ast node.

This breaks IPython, as if this string is the only expression, IPython
will not return it as the result of the current cell.
"""
from ast import Str, Expr, Module, fix_missing_locations
docstring = getattr(module, 'docstring', None)
if not docstring:
return module
new_body=[Expr(Str(docstring, lineno=1, col_offset=0), lineno=1, col_offset=0)]
new_body.extend(module.body)
return fix_missing_locations(Module(new_body))

def ast_parse(self, source, filename='<unknown>', symbol='exec'):
"""Parse code to an AST with the current compiler flags active.

Arguments are exactly the same as ast.parse (in the standard library),
and are passed to the built-in compile function."""
return self._fix_module_ds(compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1))
return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)

def reset_compiler_flags(self):
"""Reset compiler flags to default state."""
# This value is copied from codeop.Compile.__init__, so if that ever
Expand Down
8 changes: 8 additions & 0 deletions IPython/core/interactiveshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -2756,6 +2756,14 @@ def error_before_exec(value):
# Compile to bytecode
try:
code_ast = compiler.ast_parse(cell, filename=cell_name)
# Python 3.7: some single statements (bare strings) can be treated
# differently and won't result in nodes in the body.
# Recompile with 'single' and reconstruct a Module from the resulting
# Interactive node.
if len(code_ast.body) == 0:
interactive = compiler.ast_parse(
cell, filename=cell_name, symbol="single")
code_ast = ast.Module(interactive.body)
except self.custom_exceptions as e:
etype, value, tb = sys.exc_info()
self.CustomTB(etype, value, tb)
Expand Down