How do you specify and enforce an interface spec in Python?

Let us first see what is an interface spec. The interface spec is an interface specification for a module provided by programming languages such as C++ and Java. It describes the prototypes for the methods and functions of the module.

The abc module

The abc module introduced in Python 2.6 to define Abstract Base Classes (ABCs). Use the isinstance() and issubclass() to check whether an instance or a class implements a particular Abstract Base Class. With that, the module defines a set of useful ABCs such as Iterable, Container, and MutableMapping.

The collections module has classes that derive from ABCs. The submodule has some ABCs that can be used to test whether a class or instance provides a particular interface.

The rewards of interface specifications can be attained by a suitable test discipline in Python −

Test Suite

A good test suite for a module can both provide a regression test and serve as a module interface specification and a set of examples. Many Python modules can be run as a script to provide a simple self test.

Stub Emulations

Even modules which use complex external interfaces can often be tested in isolation using trivial “stub” emulations of the external interface.

Create Test Suits with the doctest and unittest modules

The doctest and unittest modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module.

The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.

The unittest module supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

Build Large Complex Application

A suitable testing discipline can help build large complex applications in Python as well as having interface specifications would.

Test-Driven Development

Writing test suites is very helpful, and you might want to design your code to make it easily tested. One increasingly popular technique, test-driven development, calls for writing parts of the test suite first, before you write any of the actual code.