ast
moduleThe ast
module (where ast
stands for
This module helps applications to process trees of syntax and find out what the current syntax grammar looks like programmatically. Abstract syntax trees are great tools for program analysis and program transformation systems.
ast.Nonlocal
methodast.Nonlocal(names)
is a class defined in the ast
module that expresses a nonlocal
statement in Python in the form of an Abstract Syntax Tree.
When the parse()
method of ast
is called on a Python source code that contains nonlocal
statements, the ast.Nonlocal
class is invoked. This expresses the nonlocal
statement to a node in an ast
tree data structure. The ast.Nonlocal
class represents the Nonlocal
node type in the ast
tree.
names
: A list of raw strings.The following Python code illustrates an example of the ast.Nonlocal
class.
import ast from pprint import pprint class NonlocalVisitor(ast.NodeVisitor): def visit_Nonlocal(self, node): print('Node type: Nonlocal\nFields: ', node._fields) self.generic_visit(node) visitor = NonlocalVisitor() tree = ast.parse(""" nonlocal a,b,c """) pprint(ast.dump(tree)) visitor.visit(tree)
NonlocalVisitor
class that extends from the ast.NodeVisitor
parent class. We override the predefined visit_Nonlocal
method in the parent class, which receives the Nonlocal
node.generic_visit()
method to visit the children nodes of the input node.NonlocalVisitor
in line 18.nonlocal
statement in Python and send it to the ast.parse()
method, which returns the result of the expression after evaluation, and then stores this result in tree
.ast.dump()
method returns a formatted string of the tree structure in tree
. You can observe the string returned by the dump
function in the output of the code.visit
method available to the visitor
object visits all the nodes in the tree structure.RELATED TAGS
CONTRIBUTOR
View all Courses