diff --git a/IPython/core/compilerop.py b/IPython/core/compilerop.py index 585eba2..f5124fc 100644 --- a/IPython/core/compilerop.py +++ b/IPython/core/compilerop.py @@ -28,6 +28,7 @@ Authors from __future__ import print_function # Stdlib imports +from ast import PyCF_ONLY_AST import codeop import hashlib import linecache @@ -77,6 +78,16 @@ class CachingCompiler(codeop.Compile): # stdlib that call it outside our control go through our codepath # (otherwise we'd lose our tracebacks). linecache.checkcache = self.check_cache + + def ast_parse(self, source, filename='', symbol='exec'): + """Parse code to an AST with the current compiler flags active.""" + 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 + # changes, it will need to be updated. + self.flags = codeop.PyCF_DONT_IMPLY_DEDENT @property def compiler_flags(self): diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 58bca58..6f50046 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -2281,7 +2281,7 @@ class InteractiveShell(SingletonConfigurable, Magic): with self.display_trap: try: - code_ast = ast.parse(cell, filename=cell_name) + code_ast = self.compile.ast_parse(cell, filename=cell_name) except IndentationError: self.showindentationerror() self.execution_count += 1 diff --git a/IPython/core/tests/test_interactiveshell.py b/IPython/core/tests/test_interactiveshell.py index a256cff..e40f624 100644 --- a/IPython/core/tests/test_interactiveshell.py +++ b/IPython/core/tests/test_interactiveshell.py @@ -122,3 +122,14 @@ class InteractiveShellTestCase(unittest.TestCase): import IPython.core.formatters f = IPython.core.formatters.PlainTextFormatter() f([Spam(),Spam()]) + + def test_future_flags(self): + """Check that future flags are used for parsing code (gh-777)""" + ip = get_ipython() + ip.run_cell('from __future__ import print_function') + try: + ip.run_cell('prfunc_return_val = print(1,2, sep=" ")') + assert 'prfunc_return_val' in ip.user_ns + finally: + # Reset compiler flags so we don't mess up other tests. + ip.compile.reset_compiler_flags()