import ast # Create an AST node for loading the value of variable x x_load = ast.Load() # Create a variable reference for variable x using the ast.Name node x_ref = ast.Name(id='x', ctx=x_load) # Print the resulting node print(ast.dump(x_ref))
'Name(id=\\'x\\', ctx=Load())'
import ast # Create a list of integers nums = [1, 2, 3, 4, 5] # Create an AST node for loading the value of the list list_load = ast.Load() # Create a variable reference for the list using the ast.Name node list_ref = ast.Name(id='nums', ctx=list_load) # Create an AST node for accessing the second element of the list using the ast.Index node index = ast.Index(value=ast.Num(n=1)) subscript = ast.Subscript(value=list_ref, slice=index, ctx=list_load) # Print the resulting node print(ast.dump(subscript))This code creates an AST node that loads the value of a list "nums", accesses the second element of the list using the "Index" node and then prints the resulting AST node. In both examples, we import the "ast" package library to use the python ast nodes.