ast.arg
is a class defined in the ast
module that expresses a single argument, in a Python list, in the form of an Abstract Syntax Tree. When the parse()
method of ast
is called on the Python source code that contains an argument, the ast.arg
class is invoked. This class expresses the argument statement to a node in an ast
tree data structure. The ast.arg
class represents the arg node type in the ast
tree.
arg
: a raw string of argument name
.annotation
: annotation of the argument. Can be Str
or Name
nodes.type_comment
: an optional string with the type annotation as a comment.import astfrom pprint import pprintclass ArgVisitor(ast.NodeVisitor):def visit_arg(self, node):print('Node type: arg\nFields:', node._fields)ast.NodeVisitor.generic_visit(self, node)def visit_Name(self, node):print('Node type: Name\nFields:', node._fields)ast.NodeVisitor.generic_visit(self, node)def visit_FunctionDef(self, node):print('Node type: FunctionDef\nFields:', node._fields)ast.NodeVisitor.generic_visit(self, node)def visit_BinOp(self, node):print('Node type: BinOp\nFields:', node._fields)ast.NodeVisitor.generic_visit(self, node)visitor = ArgVisitor()tree = ast.parse("""def add(a, b):return a + b""")pprint(ast.dump(tree))visitor.visit(tree)
ArgVisitor
class that extends from the parent class ast.NodeVisitor
.visit_arg
, visit_BinOp
, visit_Name
, and visit_FunctionDef
methods in the parent class, which receive the arg
, BinOp
, Name
, and FunctionDef
nodes, respectively.generic_visit()
method, which invokes the propagation of visit on the children nodes of the input node.ArgVisitor
.ast.parse()
method, which returns the result of the expression after evaluation and store the result in a tree.ast.dump()
method returns a formatted string of the tree structure in a tree.visit
method available to the visitor object visits all the nodes in the tree structure.