Public
Snippet $475 authored by Jérome Perrin

Rewrite divisions for runtime inspection

Edited
rewrite_div.py
Raw
import lib2to3.fixer_base
import lib2to3.fixer_util
import lib2to3.pgen2
import sys


class FixRewriteDiv(lib2to3.fixer_base.BaseFix):
  """Rewrites a/b into division_traced(a, b)

  division_traced can be a function that looks up the stack and record the operand types, for example:

      def division_traced(dividend, divisor):
        import inspect
        previous_frame = inspect.currentframe().f_back
        print ("{}:{} {} / {}".format(
            previous_frame.f_code.co_filename,
            previous_frame.f_lineno,
            type(dividend),
            type(divisor)
        ))
        return dividend / divisor

      import __builtin__
      __builtin__.division_traced = division_traced

  """

  def match(self, node):
    return (
        len(node.children) == 3 and
        node.children[1].type == lib2to3.pgen2.token.SLASH)

  def transform(self, node, results):
    node.replace(
        lib2to3.fixer_util.Call(
            lib2to3.fixer_util.Name("division_traced"),
            args=(
                node.children[0].clone(),
                lib2to3.fixer_util.Comma(),
                node.children[2].clone(),
            ),
            prefix=node.prefix))


import lib2to3.refactor
refactoring_tool = lib2to3.refactor.RefactoringTool(
    fixer_names=('rewrite_div',)) # ( this script must be named rewrite_div.py )

for script_name in sys.argv[1:]:
  with open(script_name) as f:
    new_code = refactoring_tool.refactor_string(f.read(), script_name)
  with open(script_name, 'w') as f:
    f.write(str(new_code))
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!