7. 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?
15. 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)
16. 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=[]))])
17. 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