Using Python’s Tabnanny Module for Cleaner Code

In Python, you will find many white spaces or tabs in the code to clean such unclear identification we have a tabnanny module to use. The tabnanny module gives a scanner to report on the ambiguous use of indentation. Check out Python’s Tabnanny Module for Cleaner Code Tutorial and find the ways to process the tabnanny module in python.

In Using Python’s Tabnanny Module for Cleaner Code Tutorial, you’ll learn: 

The tabnanny Module in Python

Tabnanny is a module in Python that checks your source code for ambiguous indentation. This module is helpful very well in Python, because white space isn’t supposed to be ambiguous, and if your source code contains any weird combinations of tabs and spaces, tabnanny will let you know. For instance, you can see the below code:

#!/usr/bin/python
r1 = 10
r2 = 20
sum = vara + varb
print "vara + varb = %d" % sum

In case you will test a correct file with tabnanny.py, then it will not complain as follows:

$tabnanny.py -v sum.py
'sum.py': Clean bill of health.

Check More: Build Games Python Using Pygame

Running from the Command Line

You can run tabnanny in one of two ways, either by using the command line or by running it within your program. Running it from the command line would look something like this:

$ python -m tabnanny .

This will yield results that specify which file and which line an error has been found in. If you want to see more info about all the files that are being scanned, use the -v option when writing your command:

$ python -m tabnanny -v .

Using within Your Program

To run tabnanny from within your program, you’ll need to use it with the function .check(), which should look something like this:

import sys 
import tabnanny 

tabnanny.check(file_or_dir)

If you use tabnanny to check all your code, you should never have any problems with indentation errors. As the process is normally very fast and needs hardly any coding to finish, it’s sort of a no-brainer.

Here’s another instance of using tabnanny that doesn’t need knowledge of Paver’s task definition decorators.

import sys
import tabnanny

# Turn on verbose mode
tabnanny.verbose = 1

for dirname in sys.argv[1:]:
    tabnanny.check(dirname)

Leave a Reply

Your email address will not be published. Required fields are marked *