ยปCore Development>Code coverage>Lib/lib2to3/fixes/fix_print.py

Python code coverage for Lib/lib2to3/fixes/fix_print.py

#countcontent
1n/a# Copyright 2006 Google, Inc. All Rights Reserved.
2n/a# Licensed to PSF under a Contributor Agreement.
3n/a
4n/a"""Fixer for print.
5n/a
6n/aChange:
7n/a 'print' into 'print()'
8n/a 'print ...' into 'print(...)'
9n/a 'print ... ,' into 'print(..., end=" ")'
10n/a 'print >>x, ...' into 'print(..., file=x)'
11n/a
12n/aNo changes are applied if print_function is imported from __future__
13n/a
14n/a"""
15n/a
16n/a# Local imports
17n/afrom .. import patcomp
18n/afrom .. import pytree
19n/afrom ..pgen2 import token
20n/afrom .. import fixer_base
21n/afrom ..fixer_util import Name, Call, Comma, String
22n/a
23n/a
24n/aparend_expr = patcomp.compile_pattern(
25n/a """atom< '(' [atom|STRING|NAME] ')' >"""
26n/a )
27n/a
28n/a
29n/aclass FixPrint(fixer_base.BaseFix):
30n/a
31n/a BM_compatible = True
32n/a
33n/a PATTERN = """
34n/a simple_stmt< any* bare='print' any* > | print_stmt
35n/a """
36n/a
37n/a def transform(self, node, results):
38n/a assert results
39n/a
40n/a bare_print = results.get("bare")
41n/a
42n/a if bare_print:
43n/a # Special-case print all by itself
44n/a bare_print.replace(Call(Name("print"), [],
45n/a prefix=bare_print.prefix))
46n/a return
47n/a assert node.children[0] == Name("print")
48n/a args = node.children[1:]
49n/a if len(args) == 1 and parend_expr.match(args[0]):
50n/a # We don't want to keep sticking parens around an
51n/a # already-parenthesised expression.
52n/a return
53n/a
54n/a sep = end = file = None
55n/a if args and args[-1] == Comma():
56n/a args = args[:-1]
57n/a end = " "
58n/a if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"):
59n/a assert len(args) >= 2
60n/a file = args[1].clone()
61n/a args = args[3:] # Strip a possible comma after the file expression
62n/a # Now synthesize a print(args, sep=..., end=..., file=...) node.
63n/a l_args = [arg.clone() for arg in args]
64n/a if l_args:
65n/a l_args[0].prefix = ""
66n/a if sep is not None or end is not None or file is not None:
67n/a if sep is not None:
68n/a self.add_kwarg(l_args, "sep", String(repr(sep)))
69n/a if end is not None:
70n/a self.add_kwarg(l_args, "end", String(repr(end)))
71n/a if file is not None:
72n/a self.add_kwarg(l_args, "file", file)
73n/a n_stmt = Call(Name("print"), l_args)
74n/a n_stmt.prefix = node.prefix
75n/a return n_stmt
76n/a
77n/a def add_kwarg(self, l_nodes, s_kwd, n_expr):
78n/a # XXX All this prefix-setting may lose comments (though rarely)
79n/a n_expr.prefix = ""
80n/a n_argument = pytree.Node(self.syms.argument,
81n/a (Name(s_kwd),
82n/a pytree.Leaf(token.EQUAL, "="),
83n/a n_expr))
84n/a if l_nodes:
85n/a l_nodes.append(Comma())
86n/a n_argument.prefix = " "
87n/a l_nodes.append(n_argument)