Building Nimoy: Identifying Specifications and Features

Noam Tenne
Python Pandemonium
Published in
2 min readNov 9, 2017

Documenting the process of building Nimoy — Part 3.

In our last installment we reviewed how Nimoy finds and executes tests. Now we can dive into supporting Nimoy’s syntax.

So we’ve found all files ending with “_spec.py”. Now, remember that Python modules may contain more than one Specification class. Each class may also contain more than one Feature method. Being aware of all Specifications and Features means we can maintain context for each of them. How can we account for them all?

AST Transformations, Of Course!

I won’t go into the Python’s Abstract Syntax Tree mechanisms here. There are quite enough good tutorials out there.

In short, Python allows us to transform code into AST models. Using these models we can review or change the code before execution.

Review and modification are simple. Once we convert the code to AST objects, we traverse them using visitor utilities:

We first construct a transformer class by inheriting from ast.NodeTransformer. We then implement a visit method. Visit methods follow a specific convention. We prefix the name with visit_ and end with the type of the AST node. Traversing the tree, our visit method will execute for every instance of this type.

Finding Features In Spec Stacks

We can apply AST visitors to find both Specification classes and Feature methods.

When visiting each class, we iterate over each of its bases. Bases in plural as Python supports multiple inheritance. If a class inherits from Nimoy’s Specification class, we can register it as a Specification.

Finding Feature methods is similar:

And our requirements for Features are lax . If a method is within a Specification class and isn’t private, it’s a Feature.

Simple!

--

--