Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Hacking the Python AST

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.
Avatar for Suhas SG Suhas SG
September 25, 2016

Hacking the Python AST

Talk at Pycon India 2016
CC BY-SA 4.0

Avatar for Suhas SG

Suhas SG

September 25, 2016
Tweet

Other Decks in Programming

Transcript

  1. Grammars S –> AB A –> aA | ε B

    –> b | bB S AB S –> AB aAB A –> aA aaAB A –> aA aaaAB A –> aA aaaεB A –> ε aaab B –> b A parse of aaab Does aaab belong to this Grammar?
  2. Design of the CPython Compiler Parser/ pgen.c Python/ ast.c Python/

    compile.c Python/ compile.c Parse Tree .py file Byte code AST CFG
  3. Design of the CPython Compiler Parser/ pgen.c Python/ ast.c Python/

    compile.c Python/ compile.c Parse Tree .py file Byte code AST CFG
  4. Python to x86 and then the 01010101s Parser/ pgen.c Python/

    ast.c Python/ compile.c Python/ compile.c Parse Tree .py file Byte code AST CFG Python/ ceval.c
  5. Accessing the AST a = 26 b = 0 print(a

    + b) example.py In [1]: import ast In [2]: source = open('example.py').read() In [3]: tree = ast.parse(source)
  6. Accessing the AST a = 26 b = 0 print(a

    + b) example.py Module(body=[ Expr(value=Str(s='Docstring')), Assign( targets=[Name( id='a', ctx=Store())], value=Num(n=26)), Assign( targets=[Name( id='b', ctx=Store())], value=Num(n=0)), Expr(value=Call( func=Name( id='print', ctx=Load()), args=[BinOp( left=Name( id='a', ctx=Load()), op=Add(), right=Name( id='b', ctx=Load()))], keywords=[]))])
  7. Having a little fun, now In [3]: tree = ast.parse('x

    = 5') In [4]: print(astunparse.dump(tree)) Module(body=[Assign( targets=[Name( id='x', ctx=Store())], value=Num(n=5))]) In [5]: tree.body[0].targets[0].id Out[5]: 'x' In [6]: astunparse.unparse(tree) x = 5 In [7]: tree.body[0].targets[0].id = 'y' In [8]: print(astunparse.unparse(tree)) y = 5