Template building utilities

astcheck includes some utilities for building AST templates to care against.


Build an argument for a function definition. This returns a ast.arg node in Python 3, and a ast.Name node with ctx of ast.Param in Python 2.

astcheck.must_exist(node, path)

Checker function for an item or list that must exist

This matches any value except None and the empty list.

For instance, to match for loops with an else clause:

astcheck.must_not_exist(node, path)

Checker function for things that must not exist

This accepts only None and the empty list.

For instance, to check that a function has no decorators:


Make a checker function for ast.Name or ast.Attribute.

These are often used in similar ways - depending on how you do imports, objects will be referenced as names or as attributes of a module. By using this function to build your template, you can allow either. For instance, this will match both f() and mod.f():

class astcheck.listmiddle

Helper to check only the beginning and/or end of a list. Instantiate it and add lists to it to match them at the start or the end. E.g. to test the final return statement of a function, while ignoring any other code in the function:

template = ast.FunctionDef(name="myfunc",
     body= astcheck.listmiddle()+[ast.Return(value=ast.Name(id="retval"))]

sample = ast.parse("""
def myfunc():
    retval = do_something() * 7
    return retval

astcheck.assert_ast_like(sample.body[0], template)