#-----------------------------------------------------------------
# pycparser: serialize_ast.py
#
# Simple example of serializing AST
#
# Hart Chu [https://github.com/CtheSky]
# Eli Bendersky [http://eli.thegreenplace.net]
# License: BSD
#-----------------------------------------------------------------
from __future__ import print_function
import pickle

from pycparser import c_parser

text = r"""
void func(void)
{
  x = 1;
}
"""

parser = c_parser.CParser()
ast = parser.parse(text)

# Since AST nodes use __slots__ for faster attribute access and
# space saving, it needs Pickle's protocol version >= 2.
# The default version is 3 for python 3.x and 1 for python 2.7.
# You can always select the highest available protocol with the -1 argument.
#
f = open('ast', 'wb')
pickle.dump(ast, f, protocol=-1)
f.close()

f = open('ast', 'rb')
ast = pickle.load(f)
f.close()

ast.show()

@@ -750,13 +750,13 @@
 nt.%0A
-#%0Af =
+%0Awith
  ope
@@ -769,17 +769,27 @@
 ', 'wb')
-%0A
+ as f:%0A    
 pickle.d
@@ -817,22 +817,28 @@
 -1)%0A
-f.close()%0A%0Af =
+%0A# Deserialize.%0Awith
  ope
@@ -851,17 +851,27 @@
 ', 'rb')
-%0A
+ as f:%0A    
 ast = pi
@@ -887,19 +887,12 @@
 (f)%0A
-f.close()%0A%0A
+    
 ast.

Tweak serialize_ast sample to use `with` statements