Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

What is ast.fix_missing_locations(node) in Python?

Adnan Abbas

Python ast module

The ast module (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.

ast.fix_missing_locations method

ast.fix_missing_locations is a helper function that helps in traversing abstract syntax trees.

When an AST is compiled with the compile() function, the compiler expects the attributes:

  • line number
  • column offset

For every node that supports them. For the nodes generated already, it is rather tedious to fill in this information, so this method helps us to set these attributes recursively on all nodes.

The values set for these attributes are those of the parent node.

Parameters

  • node: is the starting node from which the function begins recursively down to its children.

Example

import ast
from pprint import pprint

m = ast.Module([ast.Expr(ast.Str(42))])
ast.fix_missing_locations(m)
tree = ast.parse(m)
pprint(ast.dump(tree))

In the example above, we generate a node m and call the fix_missing_locations function on the node which fills in all the missing attributes of the node.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring