<jupyter_start><jupyter_text>Chapter 9  Exploring the Library of AST<jupyter_code>import ast
assignment = "productName = '<NAME>'"
assignment
assign_tree = ast.parse(assignment)
assign_tree
print(ast.dump(assign_tree,indent = 4))<jupyter_output>Module(
    body=[
        Assign(
            targets=[
                Name(id='productName', ctx=Store())],
            value=Constant(value='Iphone X'))],
    type_ignores=[])<jupyter_text>Reviewing a simple code<jupyter_code>addfunc = """
a = 1098
b = 2032
c = a + b
print(c)
"""
add_tree = ast.parse(addfunc)
add_tree
print(ast.dump(add_tree, indent=4))
add_code = compile(add_tree, 'add_tree', 'exec')
exec(add_code)<jupyter_output>3130<jupyter_text>Modifying the simple code<jupyter_code>add_tree
add_tree.body[2].value.op=ast.Mult()
print(ast.dump(add_tree, indent=4))
add_code = compile(add_tree, 'add_tree', 'exec')
exec(add_code)<jupyter_output>2231136<jupyter_text>Understanding the AST of a class<jupyter_code>branch_code = """
class Branch:
    '''attributes...'''
    
    '''methods...'''

"""
branch_tree = ast.parse(branch_code)
branch_tree
print(ast.dump(branch_tree, indent=4))
branch_code = """class Branch:
    branchID = 1001

    @staticmethod
    def getProduct(self):
        return 'product'
        """
branch_tree = ast.parse(branch_code)
print(ast.dump(branch_tree, indent=4))
branch_code = """
branchAlbany = Branch()
"""
branch_tree = ast.parse(branch_code)
print(ast.dump(branch_tree, indent=4))<jupyter_output>Module(
    body=[
        Assign(
            targets=[
                Name(id='branchAlbany', ctx=Store())],
            value=Call(
                func=Name(id='Branch', ctx=Load()),
                args=[],
                keywords=[]))],
    type_ignores=[])<jupyter_text>Modifying AST of a code block by parsing<jupyter_code>vegctr = """
class VegCounter():
    def returnCart(self,*items):
        cartItems = []
        for i in items:
            cartItems.append(i)
        return cartItems
veg = VegCounter()
print(veg.returnCart('onions','tomatoes','carrots','lettuce'))
"""
vegctr_tree = ast.parse(vegctr)
print(ast.dump(vegctr_tree, indent=4))
vegctr_code = compile(vegctr_tree, 'vegctr_tree', 'exec')
exec(vegctr_code)
vegctr_tree.body
vegctr_tree.body[2].value.args[0].args[1].n
vegctr_tree.body[2].value.args[0].args[1].n = 'potatoes'
print(ast.dump(vegctr_tree, indent=4))
print(ast.unparse(vegctr_tree))<jupyter_output>class VegCounter:

    def returnCart(self, *items):
        cartItems = []
        for i in items:
            cartItems.append(i)
        return cartItems
veg = VegCounter()
print(veg.returnCart('onions', 'potatoes', 'carrots', 'lettuce'))<jupyter_text>Modifying AST of a code block by transforming nodes<jupyter_code>class VegCounter():
    def returnCart(self,*items):
        cartItems = []
        for i in items:
            cartItems.append(i)
        return cartItems
veg = VegCounter()
cart = """veg.returnCart('onions','tomatoes','carrots','lettuce')"""
cart_tree = ast.parse(cart)
print(ast.dump(cart_tree, indent = 4))
from ast import NodeTransformer
class ModifyVegCounter(NodeTransformer):
    
    def visit_Constant(self, node):
        modifiedValue = ast.Constant('item:' + str(node.value))
        return modifiedValue
ModifyVegCounter().visit(cart_tree)
print(ast.dump(cart_tree, indent = 4))
print(ast.unparse(cart_tree))<jupyter_output>veg.returnCart('item:onions', 'item:tomatoes', 'item:carrots', 'item:lettuce')
{'fraction_non_alphanumeric': 0.14825497548312663, 'fraction_numerical': 0.011825785982117105, 'mean_word_length': 4.2785388127853885, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '127518', 'license': 'MIT', 'n_tokens_mistral': 1246, 'n_tokens_neox': 1218, 'n_words': 209, 'path': 'Chapter9/Chapter9.ipynb', 'repo_name': 'PacktPublishing/Hands-On-Metaprogramming-with-Python3', 'size': '3469'}