What is ast.Await(value) in Python?
Python ast module
The ast module
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.Await method
ast.Await(value) is a class defined in the ast module that expresses an await 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 await statements, the ast.Await class is invoked. This expresses the await statement to a node in an ast tree data structure. The ast.Await class represents the Await node type in the ast tree.
The
ast.Awaitclass is only invoked in the body of an Async function.
Parameters
value: contains the value for which some function waits.
Example
The following Python code illustrates an example of the ast.Await class.
import astfrom pprint import pprintclass AwaitVisitor(ast.NodeVisitor):def visit_Await(self, node):print('Node type: Await\nFields: ', node._fields)self.generic_visit(node)def visit_Call(self,node):print('Node type: Call\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)visitor = AwaitVisitor()tree = ast.parse("""async def someFunc():await other_func()""")pprint(ast.dump(tree))visitor.visit(tree)
Code description
- We define a
AwaitVisitorclass that extends from theast.NodeVisitorparent class. We override the predefinedvisit_Await,visit_Call, andvisit_Namemethods in the parent class, which receive theAwait,Call, andNamenodes, respectively. - In these methods, we print the type and the fields inside the node and call the
generic_visit()method to visit the children nodes of the input node. - We initialize a visitor object of the class
AwaitVisitor(line 18). - We write a definition of a Python asynchronous function and send it to the
ast.parse()method, which returns the result of the expression after evaluation, and then stores this result intree. - The
ast.dump()method returns a formatted string of the tree structure intree. You can observe the string returned by thedumpfunction in the output of the code. - The inbuilt
visitmethod available to thevisitorobject visits all the nodes in the tree structure.