OLD | NEW |
(Empty) | |
| 1 """Fixer for 'raise E, V' |
| 2 |
| 3 From Armin Ronacher's ``python-modernize``. |
| 4 |
| 5 raise -> raise |
| 6 raise E -> raise E |
| 7 raise E, V -> raise E(V) |
| 8 |
| 9 raise (((E, E'), E''), E'''), V -> raise E(V) |
| 10 |
| 11 |
| 12 CAVEATS: |
| 13 1) "raise E, V" will be incorrectly translated if V is an exception |
| 14 instance. The correct Python 3 idiom is |
| 15 |
| 16 raise E from V |
| 17 |
| 18 but since we can't detect instance-hood by syntax alone and since |
| 19 any client code would have to be changed as well, we don't automate |
| 20 this. |
| 21 """ |
| 22 # Author: Collin Winter, Armin Ronacher |
| 23 |
| 24 # Local imports |
| 25 from lib2to3 import pytree, fixer_base |
| 26 from lib2to3.pgen2 import token |
| 27 from lib2to3.fixer_util import Name, Call, is_tuple |
| 28 |
| 29 class FixRaise(fixer_base.BaseFix): |
| 30 |
| 31 BM_compatible = True |
| 32 PATTERN = """ |
| 33 raise_stmt< 'raise' exc=any [',' val=any] > |
| 34 """ |
| 35 |
| 36 def transform(self, node, results): |
| 37 syms = self.syms |
| 38 |
| 39 exc = results["exc"].clone() |
| 40 if exc.type == token.STRING: |
| 41 msg = "Python 3 does not support string exceptions" |
| 42 self.cannot_convert(node, msg) |
| 43 return |
| 44 |
| 45 # Python 2 supports |
| 46 # raise ((((E1, E2), E3), E4), E5), V |
| 47 # as a synonym for |
| 48 # raise E1, V |
| 49 # Since Python 3 will not support this, we recurse down any tuple |
| 50 # literals, always taking the first element. |
| 51 if is_tuple(exc): |
| 52 while is_tuple(exc): |
| 53 # exc.children[1:-1] is the unparenthesized tuple |
| 54 # exc.children[1].children[0] is the first element of the tuple |
| 55 exc = exc.children[1].children[0].clone() |
| 56 exc.prefix = u" " |
| 57 |
| 58 if "val" not in results: |
| 59 # One-argument raise |
| 60 new = pytree.Node(syms.raise_stmt, [Name(u"raise"), exc]) |
| 61 new.prefix = node.prefix |
| 62 return new |
| 63 |
| 64 val = results["val"].clone() |
| 65 if is_tuple(val): |
| 66 args = [c.clone() for c in val.children[1:-1]] |
| 67 else: |
| 68 val.prefix = u"" |
| 69 args = [val] |
| 70 |
| 71 return pytree.Node(syms.raise_stmt, |
| 72 [Name(u"raise"), Call(exc, args)], |
| 73 prefix=node.prefix) |
OLD | NEW |