fix_print.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # Copyright 2006 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Fixer for print.
  4. Change:
  5. "print" into "print()"
  6. "print ..." into "print(...)"
  7. "print(...)" not changed
  8. "print ... ," into "print(..., end=' ')"
  9. "print >>x, ..." into "print(..., file=x)"
  10. No changes are applied if print_function is imported from __future__
  11. """
  12. # Local imports
  13. from lib2to3 import patcomp, pytree, fixer_base
  14. from lib2to3.pgen2 import token
  15. from lib2to3.fixer_util import Name, Call, Comma, String
  16. # from libmodernize import add_future
  17. parend_expr = patcomp.compile_pattern(
  18. """atom< '(' [arith_expr|atom|power|term|STRING|NAME] ')' >"""
  19. )
  20. class FixPrint(fixer_base.BaseFix):
  21. BM_compatible = True
  22. PATTERN = """
  23. simple_stmt< any* bare='print' any* > | print_stmt
  24. """
  25. def transform(self, node, results):
  26. assert results
  27. bare_print = results.get("bare")
  28. if bare_print:
  29. # Special-case print all by itself.
  30. bare_print.replace(Call(Name(u"print"), [],
  31. prefix=bare_print.prefix))
  32. # The "from __future__ import print_function"" declaration is added
  33. # by the fix_print_with_import fixer, so we skip it here.
  34. # add_future(node, u'print_function')
  35. return
  36. assert node.children[0] == Name(u"print")
  37. args = node.children[1:]
  38. if len(args) == 1 and parend_expr.match(args[0]):
  39. # We don't want to keep sticking parens around an
  40. # already-parenthesised expression.
  41. return
  42. sep = end = file = None
  43. if args and args[-1] == Comma():
  44. args = args[:-1]
  45. end = " "
  46. # try to determine if the string ends in a non-space whitespace character, in which
  47. # case there should be no space at the end of the conversion
  48. string_leaves = [leaf for leaf in args[-1].leaves() if leaf.type == token.STRING]
  49. if (
  50. string_leaves
  51. and string_leaves[-1].value[0] != "r" # "raw" string
  52. and string_leaves[-1].value[-3:-1] in (r"\t", r"\n", r"\r")
  53. ):
  54. end = ""
  55. if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, u">>"):
  56. assert len(args) >= 2
  57. file = args[1].clone()
  58. args = args[3:] # Strip a possible comma after the file expression
  59. # Now synthesize a print(args, sep=..., end=..., file=...) node.
  60. l_args = [arg.clone() for arg in args]
  61. if l_args:
  62. l_args[0].prefix = u""
  63. if sep is not None or end is not None or file is not None:
  64. if sep is not None:
  65. self.add_kwarg(l_args, u"sep", String(repr(sep)))
  66. if end is not None:
  67. self.add_kwarg(l_args, u"end", String(repr(end)))
  68. if file is not None:
  69. self.add_kwarg(l_args, u"file", file)
  70. n_stmt = Call(Name(u"print"), l_args)
  71. n_stmt.prefix = node.prefix
  72. # Note that there are corner cases where adding this future-import is
  73. # incorrect, for example when the file also has a 'print ()' statement
  74. # that was intended to print "()".
  75. # add_future(node, u'print_function')
  76. return n_stmt
  77. def add_kwarg(self, l_nodes, s_kwd, n_expr):
  78. # XXX All this prefix-setting may lose comments (though rarely)
  79. n_expr.prefix = u""
  80. n_argument = pytree.Node(self.syms.argument,
  81. (Name(s_kwd),
  82. pytree.Leaf(token.EQUAL, u"="),
  83. n_expr))
  84. if l_nodes:
  85. l_nodes.append(Comma())
  86. n_argument.prefix = u" "
  87. l_nodes.append(n_argument)