1
# Copyright 2006 Google, Inc. All Rights Reserved.
2
# Licensed to PSF under a Contributor Agreement.
8
'print ...' into 'print(...)'
9
'print ... ,' into 'print(..., end=" ")'
10
'print >>x, ...' into 'print(..., file=x)'
12
No changes are applied if print_function is imported from __future__
17
from .. import patcomp
19
from ..pgen2 import token
20
from .. import fixer_base
21
from ..fixer_util import Name, Call, Comma, String, is_tuple
24
parend_expr = patcomp.compile_pattern(
25
"""atom< '(' [atom|STRING|NAME] ')' >"""
29
class FixPrint(fixer_base.BaseFix):
34
simple_stmt< any* bare='print' any* > | print_stmt
37
def transform(self, node, results):
40
bare_print = results.get("bare")
43
# Special-case print all by itself
44
bare_print.replace(Call(Name("print"), [],
45
prefix=bare_print.prefix))
47
assert node.children[0] == Name("print")
48
args = node.children[1:]
49
if len(args) == 1 and parend_expr.match(args[0]):
50
# We don't want to keep sticking parens around an
51
# already-parenthesised expression.
54
sep = end = file = None
55
if args and args[-1] == Comma():
58
if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"):
60
file = args[1].clone()
61
args = args[3:] # Strip a possible comma after the file expression
62
# Now synthesize a print(args, sep=..., end=..., file=...) node.
63
l_args = [arg.clone() for arg in args]
66
if sep is not None or end is not None or file is not None:
68
self.add_kwarg(l_args, "sep", String(repr(sep)))
70
self.add_kwarg(l_args, "end", String(repr(end)))
72
self.add_kwarg(l_args, "file", file)
73
n_stmt = Call(Name("print"), l_args)
74
n_stmt.prefix = node.prefix
77
def add_kwarg(self, l_nodes, s_kwd, n_expr):
78
# XXX All this prefix-setting may lose comments (though rarely)
80
n_argument = pytree.Node(self.syms.argument,
82
pytree.Leaf(token.EQUAL, "="),
85
l_nodes.append(Comma())
86
n_argument.prefix = " "
87
l_nodes.append(n_argument)