More thoroughly search for print functions when deciding whether to add from __import__ import print_function.

PiperOrigin-RevId: 231611485
This commit is contained in:
Dan Moldovan 2019-01-30 09:44:48 -08:00 committed by TensorFlower Gardener
parent 1e9e2a7003
commit 040a993db3
2 changed files with 11 additions and 1 deletions

View File

@ -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

View File

@ -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