29
class FixPrint(fixer_base.ConditionalFix):
29
class FixPrint(fixer_base.BaseFix):
32
32
simple_stmt< any* bare='print' any* > | print_stmt
35
skip_on = '__future__.print_function'
37
35
def transform(self, node, results):
40
if self.should_skip(node):
43
38
bare_print = results.get("bare")
46
41
# Special-case print all by itself
47
bare_print.replace(Call(Name("print"), [],
48
prefix=bare_print.get_prefix()))
42
bare_print.replace(Call(Name(u"print"), [],
43
prefix=bare_print.prefix))
50
assert node.children[0] == Name("print")
45
assert node.children[0] == Name(u"print")
51
46
args = node.children[1:]
52
47
if len(args) == 1 and parend_expr.match(args[0]):
53
48
# We don't want to keep sticking parens around an
58
53
if args and args[-1] == Comma():
61
if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"):
56
if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, u">>"):
62
57
assert len(args) >= 2
63
58
file = args[1].clone()
64
59
args = args[3:] # Strip a possible comma after the file expression
65
60
# Now synthesize a print(args, sep=..., end=..., file=...) node.
66
61
l_args = [arg.clone() for arg in args]
68
l_args[0].set_prefix("")
63
l_args[0].prefix = u""
69
64
if sep is not None or end is not None or file is not None:
70
65
if sep is not None:
71
self.add_kwarg(l_args, "sep", String(repr(sep)))
66
self.add_kwarg(l_args, u"sep", String(repr(sep)))
72
67
if end is not None:
73
self.add_kwarg(l_args, "end", String(repr(end)))
68
self.add_kwarg(l_args, u"end", String(repr(end)))
74
69
if file is not None:
75
self.add_kwarg(l_args, "file", file)
76
n_stmt = Call(Name("print"), l_args)
77
n_stmt.set_prefix(node.get_prefix())
70
self.add_kwarg(l_args, u"file", file)
71
n_stmt = Call(Name(u"print"), l_args)
72
n_stmt.prefix = node.prefix
80
75
def add_kwarg(self, l_nodes, s_kwd, n_expr):
81
76
# XXX All this prefix-setting may lose comments (though rarely)
83
78
n_argument = pytree.Node(self.syms.argument,
85
pytree.Leaf(token.EQUAL, "="),
80
pytree.Leaf(token.EQUAL, u"="),
88
83
l_nodes.append(Comma())
89
n_argument.set_prefix(" ")
84
n_argument.prefix = u" "
90
85
l_nodes.append(n_argument)