From d6db1c12a8e14833fe22da377cddc2bd1f43dc14 Mon Sep 17 00:00:00 2001 From: Andy Freeland Date: Thu, 14 Mar 2019 16:42:54 -0700 Subject: [PATCH] Fix print() function on Python 2 (#754) Fixes #752 --- black.py | 4 ++-- tests/data/python2_print_function.py | 16 ++++++++++++++++ tests/test_black.py | 8 ++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100755 tests/data/python2_print_function.py diff --git a/black.py b/black.py index b727666..c44bc9b 100644 --- a/black.py +++ b/black.py @@ -726,13 +726,13 @@ def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): - # Python 2-compatible code, so don't try Python 3 grammar. + # Python 3-compatible code, so don't try Python 2 grammar return [ pygram.python_grammar_no_print_statement_no_exec_statement, pygram.python_grammar_no_print_statement, ] else: - return [pygram.python_grammar] + return [pygram.python_grammar_no_print_statement, pygram.python_grammar] def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node: diff --git a/tests/data/python2_print_function.py b/tests/data/python2_print_function.py new file mode 100755 index 0000000..81b8d8a --- /dev/null +++ b/tests/data/python2_print_function.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python2 +from __future__ import print_function + +print('hello') +print(u'hello') +print(a, file=sys.stderr) + +# output + + +#!/usr/bin/env python2 +from __future__ import print_function + +print("hello") +print(u"hello") +print(a, file=sys.stderr) diff --git a/tests/test_black.py b/tests/test_black.py index 7c99f00..645eec7 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -461,6 +461,14 @@ class BlackTestCase(unittest.TestCase): # black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) + @patch("black.dump_to_file", dump_to_stderr) + def test_python2_print_function(self) -> None: + source, expected = read_data("python2_print_function") + mode = black.FileMode(target_versions={black.TargetVersion.PY27}) + actual = fs(source, mode=mode) + self.assertFormatEqual(expected, actual) + black.assert_stable(source, actual, mode) + @patch("black.dump_to_file", dump_to_stderr) def test_python2_unicode_literals(self) -> None: source, expected = read_data("python2_unicode_literals") -- 2.39.5