/Lib/lib2to3/fixes/fix_except.py

http://unladen-swallow.googlecode.com/ · Python · 92 lines · 63 code · 12 blank · 17 comment · 16 complexity · 52aa418ea43fa6456fa38109fa3876c9 MD5 · raw file

  1. """Fixer for except statements with named exceptions.
  2. The following cases will be converted:
  3. - "except E, T:" where T is a name:
  4. except E as T:
  5. - "except E, T:" where T is not a name, tuple or list:
  6. except E as t:
  7. T = t
  8. This is done because the target of an "except" clause must be a
  9. name.
  10. - "except E, T:" where T is a tuple or list literal:
  11. except E as t:
  12. T = t.args
  13. """
  14. # Author: Collin Winter
  15. # Local imports
  16. from .. import pytree
  17. from ..pgen2 import token
  18. from .. import fixer_base
  19. from ..fixer_util import Assign, Attr, Name, is_tuple, is_list
  20. def find_excepts(nodes):
  21. for i, n in enumerate(nodes):
  22. if isinstance(n, pytree.Node):
  23. if n.children[0].value == 'except':
  24. yield (n, nodes[i+2])
  25. class FixExcept(fixer_base.BaseFix):
  26. PATTERN = """
  27. try_stmt< 'try' ':' suite
  28. cleanup=(except_clause ':' suite)+
  29. tail=(['except' ':' suite]
  30. ['else' ':' suite]
  31. ['finally' ':' suite]) >
  32. """
  33. def transform(self, node, results):
  34. syms = self.syms
  35. tail = [n.clone() for n in results["tail"]]
  36. try_cleanup = [ch.clone() for ch in results["cleanup"]]
  37. for except_clause, e_suite in find_excepts(try_cleanup):
  38. if len(except_clause.children) == 4:
  39. (E, comma, N) = except_clause.children[1:4]
  40. comma.replace(Name("as", prefix=" "))
  41. if N.type != token.NAME:
  42. # Generate a new N for the except clause
  43. new_N = Name(self.new_name(), prefix=" ")
  44. target = N.clone()
  45. target.set_prefix("")
  46. N.replace(new_N)
  47. new_N = new_N.clone()
  48. # Insert "old_N = new_N" as the first statement in
  49. # the except body. This loop skips leading whitespace
  50. # and indents
  51. #TODO(cwinter) suite-cleanup
  52. suite_stmts = e_suite.children
  53. for i, stmt in enumerate(suite_stmts):
  54. if isinstance(stmt, pytree.Node):
  55. break
  56. # The assignment is different if old_N is a tuple or list
  57. # In that case, the assignment is old_N = new_N.args
  58. if is_tuple(N) or is_list(N):
  59. assign = Assign(target, Attr(new_N, Name('args')))
  60. else:
  61. assign = Assign(target, new_N)
  62. #TODO(cwinter) stopgap until children becomes a smart list
  63. for child in reversed(suite_stmts[:i]):
  64. e_suite.insert_child(0, child)
  65. e_suite.insert_child(i, assign)
  66. elif N.get_prefix() == "":
  67. # No space after a comma is legal; no space after "as",
  68. # not so much.
  69. N.set_prefix(" ")
  70. #TODO(cwinter) fix this when children becomes a smart list
  71. children = [c.clone() for c in node.children[:3]] + try_cleanup + tail
  72. return pytree.Node(node.type, children)