0

I need to modify math expression from

wave_y + .3 * sin(time * .788) + .005 * (frame % 3)

to

wave_y + .3 * sin(time * .788) + .005 * fmodf(frame, 3)

To do this I write own Transformator

class PercentToFmodTransformer(ast.NodeTransformer):
    def visit_BinOp(self, node):
        if type(node.op).__name__ == 'Mod':
            result = ast.Call()
            result.func = ast.Name(id='fmodf', ctx=ast.Load())
            result.args = [node.left, node.right]
            result.keywords = []
            result.starargs = None
            result.kwargs = None

            return result
        else:
            return ast.NodeTransformer.generic_visit(self, node)

After transformation I have Expression

Expression(
body=BinOp(
    left=BinOp(
        left=Name(id='wave_y', ctx=Load()), 
        op=Add(), 
        right=BinOp(
            left=Num(n=0.3), 
            op=Mult(), 
            right=Call(
                func=Name(id='sin', ctx=Load()), 
                args=[BinOp(left=Name(id='time', ctx=Load()), op=Mult(), right=Num(n=0.788))], 
                keywords=[], 
                starargs=None, 
                kwargs=None)
            )
        ), 
        op=Add(), 
        right=BinOp(
            left=Num(n=0.005), 
            op=Mult(), 
            right=Call(
                func=Name(id='fmodf', ctx=Load()), 
                args=[Num(n=3), Name(id='frame', ctx=Load())], 
                keywords=[], 
                starargs=None, 
                kwargs=None
            )
        )
    )
)

But I don't know how to print it in human-readable format. Can this be done my some default function Or I should write own visitor for this?

P.S. I don't ask to write the implementation of this Visitor for me, I just want to know is possible to do this by inbox API.

CAMOBAP
  • 5,523
  • 8
  • 58
  • 93
  • 1
    Two notes on your code: use `isinstance(node.op, ast.Mod)` instead of `type(node.op).__name__ == 'Mod'`, and you need to visit your `node.left` and `node.right` nodes with the node transformer otherwise nested expressions are ignored. – Martijn Pieters Aug 21 '14 at 09:05
  • But what about human-readable format. Is there any 'default' function/class to do this? – CAMOBAP Aug 21 '14 at 09:08
  • Closely related: [Parse a .py file, read the AST, modify it, then write back the modified source code](http://stackoverflow.com/q/768634) – Martijn Pieters Aug 21 '14 at 09:08
  • 1
    No, there is not; see http://greentreesnakes.readthedocs.org/en/latest/tofrom.html#going-backwards – Martijn Pieters Aug 21 '14 at 09:16
  • Actually the first look more close to my case. I will mark my question as duplicate – CAMOBAP Aug 21 '14 at 09:18

0 Answers0