AST checker

General description

Abstract syntax tree is a python lint package (Abstract Syntax Trees). This extension provides more detailed information and methods of tree nodes and also allows to write your own parser code.

Connecting and creating your own parser

For using this package you have to install the component astroid.

1. The first option

This unit should obligatory have the function register(linter) and also the function MANAGER.register_transform which receives two input arguments:

  • what you need  to view (unit, function, class etc.)
  • function-handler (it will handle the object specified by the first argument).

Necessary methods for connecting

from astroid import MANAGER
from astroid import scoped_nodes

Information about nodes. It is based on connecting plugins for pylint. For that you need to create a separate python unit.

2. The second option

Without using command pylint, running the separate python unit. The unit should have a class inherited from the class NodeVisitor.

The class contains functions in the next format:

def visit_NameNodes(self,node):

NameNodes – the node for viewing. The list of nodes.

Necessary methods for connecting

import ast

Examples of using

  1. The first variant of implementation:
from astroid import MANAGER 
from astroid import scoped_nodes 
NAME_DEF_GET_PLUGIN_RESOURCE = 'getPluginResources' NAME_DEF_GET_PLUGIN_INFO = 'getPluginInfo' def transform(cls):  

   if NAME_DEF_GET_PLUGIN_RESOURCE not in cls.locals \          
    or NAME_DEF_GET_PLUGIN_INFO not in cls.locals:  
      print '======= Module: ' + cls.name + ' ======='    

   if NAME_DEF_GET_PLUGIN_RESOURCE not in cls.locals:     
     print 'No required function ' + NAME_DEF_GET_PLUGIN_RESOURCE   

   if NAME_DEF_GET_PLUGIN_INFO not in cls.locals:       
    print 'No required function ' + NAME_DEF_GET_PLUGIN_INFO

 def register(_):   
  pass

 MANAGER.register_transform(scoped_nodes.Module, transform)

This unit checks whether functions getPluginResources and getPluginInfo are contained in the unit specified for checking pylint.

The second variant of implementation:

import ast


def read_code(file_name):
    f = open(file_name, 'rt')
    code = ''.join(f.readlines())
    return code


class FuncLister(ast.NodeVisitor):
    def visit_FunctionDef(self, node):
        print node.name


code = read_code('test.py')
tree = ast.parse(code)
FuncLister().visit(tree)
2. This unit outputs names of the all functions of file test.py.

ShareShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on VKEmail this to someone