The tabnanny module

(New in 2.0) This module checks Python source files for ambigous indentation. If a file mixes tabs and spaces in a way that the indentation isn’t clear, no matter what tab size you’re using, the nanny complains.

In the file used in the following examples, the first line after the if statement uses four spaces followed by a tab. The second uses spaces only.

$ -v samples/
'samples/': *** Line 3: trouble in tab city! ***
offending line: '        print "world"\012'
indent not equal e.g. at tab sizes 1, 2, 3, 5, 6, 7, 9

Since the Python interpreter interprets a tab as eight spaces, the script will run correctly. It will also display correctly, in any editor that assumes that a tab is either eight or four spaces. That’s not enough to fool the tab nanny, of course…

You can also use tabnanny from your own programs.

Example: Using the tabnanny module
# File:

import tabnanny

FILE = "samples/"

file = open(FILE)
for line in file.readlines():
    print repr(line)

# let tabnanny look at it

$ python
'if 1:\012'
'    \011print "hello"\012'
'        print "world"\012'
samples/ 3 '        print "world"\012'

To capture the output, you can redirect sys.stdout to a StringIO object.

import tabnanny
import StringIO, sys

FILE = "samples/"

stdout = sys.stdout
    sys.stdout = StringIO.StringIO()
    output = sys.stdout.getvalue()
    sys.stdout = stdout

if output:
    print "***", "tab problems in", FILE
    print output

A Django site. rendered by a django application. hosted by webfaction.