Detection of ambiguous indentation in python

Indentation is a crucial feature of Python syntax. Code blocks in functions, classes, or loops must follow the same indent level for all statements within them. The tabnanny module in Python's standard library can detect violations in proper indentation.

This module is primarily intended for command line usage with the -m switch, but it can also be imported in an interpreter session to check Python files for indentation problems.

Command Line Usage

To check a Python file for indentation issues, use the following command ?

python -m tabnanny -q example.py

For verbose output that shows detailed information, use the -v switch ?

python -m tabnanny -v example.py

Programmatic Usage

The tabnanny module provides functions for checking indentation programmatically within your Python code.

check() Function

This function checks for ambiguously indented lines in a given file. You can also pass a directory as a parameter, and all Python files in it will be recursively checked ?

import tabnanny

# Check a single file
try:
    tabnanny.check('example.py')
    print("No indentation issues found")
except Exception as e:
    print(f"Indentation issue detected: {e}")

Creating a Test File with Indentation Issues

Let's create a simple example to demonstrate how tabnanny detects indentation problems ?

# Creating a file with mixed indentation (tabs and spaces)
test_code = '''def example_function():
    print("This line uses 4 spaces")
	print("This line uses a tab")  # This will cause an issue
    return True
'''

with open('mixed_indent.py', 'w') as f:
    f.write(test_code)

# Now check the file
import tabnanny
try:
    tabnanny.check('mixed_indent.py')
except Exception as e:
    print("Indentation error detected!")

Configuration Flags

The tabnanny module provides several flags to control its behavior ?

tabnanny.verbose

This flag indicates whether to print verbose messages. It is incremented by the -v option when called as a script ?

import tabnanny

# Enable verbose output
tabnanny.verbose = 1
tabnanny.check('example.py')

tabnanny.filename_only

This flag indicates whether to print only the filenames of files containing whitespace-related problems. It is set to True by the -q option when called as a script ?

import tabnanny

# Show only filenames with issues
tabnanny.filename_only = True
tabnanny.check('example.py')

process_tokens() Function

This function is used internally by check() to process tokens generated by the tokenize module. It raises a NannyNag exception when ambiguous indentation is detected, which is then captured and handled by the check() function.

Best Practices

To avoid indentation issues in Python ?

  • Use either spaces or tabs consistently throughout your code
  • Configure your editor to show whitespace characters
  • Use 4 spaces per indentation level (PEP 8 recommendation)
  • Run tabnanny regularly on your codebase

Conclusion

The tabnanny module is a valuable tool for maintaining consistent indentation in Python code. Use it from the command line for quick checks or import it programmatically for automated code quality checks. Consistent indentation prevents hard-to-debug syntax errors and improves code readability.

Updated on: 2026-03-25T05:27:26+05:30

675 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements