/Lib/lib2to3/fixes/fix_execfile.py

http://unladen-swallow.googlecode.com/ · Python · 51 lines · 31 code · 7 blank · 13 comment · 2 complexity · f968686ed347fd544fc69fd9cb6073cd MD5 · raw file

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