From 040a993db329aa98bc17f9d5f744d14753b36f1d Mon Sep 17 00:00:00 2001 From: Dan Moldovan Date: Wed, 30 Jan 2019 09:44:48 -0800 Subject: [PATCH] More thoroughly search for print functions when deciding whether to add from __import__ import print_function. PiperOrigin-RevId: 231611485 --- tensorflow/python/autograph/pyct/parser.py | 3 ++- tensorflow/python/autograph/pyct/parser_test.py | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/tensorflow/python/autograph/pyct/parser.py b/tensorflow/python/autograph/pyct/parser.py index a14966e470a..011d80dd62a 100644 --- a/tensorflow/python/autograph/pyct/parser.py +++ b/tensorflow/python/autograph/pyct/parser.py @@ -21,6 +21,7 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function +import re import textwrap import gast @@ -105,7 +106,7 @@ def parse_str(src): """Returns the AST of given piece of code.""" # TODO(mdan): This should exclude the module things are autowrapped in. - if six.PY2 and '.print(' in src: + if six.PY2 and re.search('\\Wprint\\(', src): # This special treatment is required because gast.parse is not aware of # whether print_function was present in the original context. src = 'from __future__ import print_function\n' + src diff --git a/tensorflow/python/autograph/pyct/parser_test.py b/tensorflow/python/autograph/pyct/parser_test.py index d3a7b7a0146..cc0123408d5 100644 --- a/tensorflow/python/autograph/pyct/parser_test.py +++ b/tensorflow/python/autograph/pyct/parser_test.py @@ -42,6 +42,15 @@ class ParserTest(test.TestCase): """)) self.assertEqual('f', mod.body[0].name) + def test_parse_str_print(self): + mod = parser.parse_str( + textwrap.dedent(""" + def f(x): + print(x) + return x + 1 + """)) + self.assertEqual('f', mod.body[0].name) + def test_parse_comments(self): def f(): # unindented comment