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

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

#countcontent
1n/a# Copyright 2006 Google, Inc. All Rights Reserved.
2n/a# Licensed to PSF under a Contributor Agreement.
3n/a
4n/a"""Fixer for execfile.
5n/a
6n/aThis converts usages of the execfile function into calls to the built-in
7n/aexec() function.
8n/a"""
9n/a
10n/afrom .. import fixer_base
11n/afrom ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node,
12n/a ArgList, String, syms)
13n/a
14n/a
15n/aclass FixExecfile(fixer_base.BaseFix):
16n/a BM_compatible = True
17n/a
18n/a PATTERN = """
19n/a power< 'execfile' trailer< '(' arglist< filename=any [',' globals=any [',' locals=any ] ] > ')' > >
20n/a |
21n/a power< 'execfile' trailer< '(' filename=any ')' > >
22n/a """
23n/a
24n/a def transform(self, node, results):
25n/a assert results
26n/a filename = results["filename"]
27n/a globals = results.get("globals")
28n/a locals = results.get("locals")
29n/a
30n/a # Copy over the prefix from the right parentheses end of the execfile
31n/a # call.
32n/a execfile_paren = node.children[-1].children[-1].clone()
33n/a # Construct open().read().
34n/a open_args = ArgList([filename.clone()], rparen=execfile_paren)
35n/a open_call = Node(syms.power, [Name("open"), open_args])
36n/a read = [Node(syms.trailer, [Dot(), Name('read')]),
37n/a Node(syms.trailer, [LParen(), RParen()])]
38n/a open_expr = [open_call] + read
39n/a # Wrap the open call in a compile call. This is so the filename will be
40n/a # preserved in the execed code.
41n/a filename_arg = filename.clone()
42n/a filename_arg.prefix = " "
43n/a exec_str = String("'exec'", " ")
44n/a compile_args = open_expr + [Comma(), filename_arg, Comma(), exec_str]
45n/a compile_call = Call(Name("compile"), compile_args, "")
46n/a # Finally, replace the execfile call with an exec call.
47n/a args = [compile_call]
48n/a if globals is not None:
49n/a args.extend([Comma(), globals.clone()])
50n/a if locals is not None:
51n/a args.extend([Comma(), locals.clone()])
52n/a return Call(Name("exec"), args, prefix=node.prefix)