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

# Python code coverage for Lib/lib2to3/fixes/fix_raise.py

#countcontent
1n/a"""Fixer for 'raise E, V, T'
2n/a
3n/araise -> raise
4n/araise E -> raise E
5n/araise E, V -> raise E(V)
6n/araise E, V, T -> raise E(V).with_traceback(T)
7n/araise E, None, T -> raise E.with_traceback(T)
8n/a
9n/araise (((E, E'), E''), E'''), V -> raise E(V)
10n/araise "foo", V, T -> warns about string exceptions
11n/a
12n/a
13n/aCAVEATS:
14n/a1) "raise E, V" will be incorrectly translated if V is an exception
15n/a instance. The correct Python 3 idiom is
16n/a
17n/a raise E from V
18n/a
19n/a but since we can't detect instance-hood by syntax alone and since
20n/a any client code would have to be changed as well, we don't automate
21n/a this.
22n/a"""
23n/a# Author: Collin Winter
24n/a
25n/a# Local imports
26n/afrom .. import pytree
27n/afrom ..pgen2 import token
28n/afrom .. import fixer_base
29n/afrom ..fixer_util import Name, Call, Attr, ArgList, is_tuple
30n/a
31n/aclass FixRaise(fixer_base.BaseFix):
32n/a
33n/a BM_compatible = True
34n/a PATTERN = """
35n/a raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] >
36n/a """
37n/a
38n/a def transform(self, node, results):
39n/a syms = self.syms
40n/a
41n/a exc = results["exc"].clone()
42n/a if exc.type == token.STRING:
43n/a msg = "Python 3 does not support string exceptions"
44n/a self.cannot_convert(node, msg)
45n/a return
46n/a
47n/a # Python 2 supports
48n/a # raise ((((E1, E2), E3), E4), E5), V
49n/a # as a synonym for
50n/a # raise E1, V
51n/a # Since Python 3 will not support this, we recurse down any tuple
52n/a # literals, always taking the first element.
53n/a if is_tuple(exc):
54n/a while is_tuple(exc):
55n/a # exc.children[1:-1] is the unparenthesized tuple
56n/a # exc.children[1].children[0] is the first element of the tuple
57n/a exc = exc.children[1].children[0].clone()
58n/a exc.prefix = " "
59n/a
60n/a if "val" not in results:
61n/a # One-argument raise
62n/a new = pytree.Node(syms.raise_stmt, [Name("raise"), exc])
63n/a new.prefix = node.prefix
64n/a return new
65n/a
66n/a val = results["val"].clone()
67n/a if is_tuple(val):
68n/a args = [c.clone() for c in val.children[1:-1]]
69n/a else:
70n/a val.prefix = ""
71n/a args = [val]
72n/a
73n/a if "tb" in results:
74n/a tb = results["tb"].clone()
75n/a tb.prefix = ""
76n/a
77n/a e = exc
78n/a # If there's a traceback and None is passed as the value, then don't
79n/a # add a call, since the user probably just wants to add a
80n/a # traceback. See issue #9661.
81n/a if val.type != token.NAME or val.value != "None":
82n/a e = Call(exc, args)
83n/a with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])]
84n/a new = pytree.Node(syms.simple_stmt, [Name("raise")] + with_tb)
85n/a new.prefix = node.prefix
86n/a return new
87n/a else:
88n/a return pytree.Node(syms.raise_stmt,
89n/a [Name("raise"), Call(exc, args)],
90n/a prefix=node.prefix)