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

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

#countcontent
1n/a"""
2n/aOptional fixer to transform set() calls to set literals.
3n/a"""
4n/a
5n/a# Author: Benjamin Peterson
6n/a
7n/afrom lib2to3 import fixer_base, pytree
8n/afrom lib2to3.fixer_util import token, syms
9n/a
10n/a
11n/a
12n/aclass FixSetLiteral(fixer_base.BaseFix):
13n/a
14n/a BM_compatible = True
15n/a explicit = True
16n/a
17n/a PATTERN = """power< 'set' trailer< '('
18n/a (atom=atom< '[' (items=listmaker< any ((',' any)* [',']) >
19n/a |
20n/a single=any) ']' >
21n/a |
22n/a atom< '(' items=testlist_gexp< any ((',' any)* [',']) > ')' >
23n/a )
24n/a ')' > >
25n/a """
26n/a
27n/a def transform(self, node, results):
28n/a single = results.get("single")
29n/a if single:
30n/a # Make a fake listmaker
31n/a fake = pytree.Node(syms.listmaker, [single.clone()])
32n/a single.replace(fake)
33n/a items = fake
34n/a else:
35n/a items = results["items"]
36n/a
37n/a # Build the contents of the literal
38n/a literal = [pytree.Leaf(token.LBRACE, "{")]
39n/a literal.extend(n.clone() for n in items.children)
40n/a literal.append(pytree.Leaf(token.RBRACE, "}"))
41n/a # Set the prefix of the right brace to that of the ')' or ']'
42n/a literal[-1].prefix = items.next_sibling.prefix
43n/a maker = pytree.Node(syms.dictsetmaker, literal)
44n/a maker.prefix = node.prefix
45n/a
46n/a # If the original was a one tuple, we need to remove the extra comma.
47n/a if len(maker.children) == 4:
48n/a n = maker.children[2]
49n/a n.remove()
50n/a maker.children[-1].prefix = n.prefix
51n/a
52n/a # Finally, replace the set call with our shiny new literal.
53n/a return maker