Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is ast.Nonlocal(names) in Python?

Adnan Abbas

Python ast module

The ast module (where ast stands for Abstract Syntax Tree)tree representation of source code allows us to interact with and modify Python code. Python comes with abstract syntax grammar that is subject to change with every Python release.

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.

The ast.Nonlocal method

ast.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)

visitor = NonlocalVisitor()
tree = ast.parse("""
nonlocal a,b,c

Code description

  • We define a 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.
  • 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 NonlocalVisitor in line 18.
  • We write a 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.
  • The 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.
  • The inbuilt visit method available to the visitor object visits all the nodes in the tree structure.



View all Courses

Keep Exploring