Source Code Spelling Correction

1.45.0 · active · verified Sun Apr 12

Typos is a fast and low false-positive source code spell checker written in Rust, provided as a Python package primarily for command-line interface (CLI) usage or integration into CI/CD workflows. It focuses on correcting a curated list of 'known misspellings' to ensure high confidence and minimize false positives. The library maintains a monthly release cadence, primarily updating its internal dictionary and applying minor fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `typos` as a command-line tool via Python's `subprocess` module. It creates a temporary file with a known typo, first checks for the typo, and then applies fixes. The `typos` tool exits with a status code of 0 if no typos are found, and 2 if typos are found and/or fixed.

import subprocess
import os

# Create a dummy file with a known typo
file_content = """\n# This is a comment with a common typo: recievice\ndef foo(arguemnt):\n    # Some code\n    pass\n"""
with open("temp_code.py", "w") as f:
    f.write(file_content)

print("--- Original file content ---")
print(file_content)

# 1. Check for typos (will exit with code 2 if typos found)
print("\n--- Checking for typos ---")
try:
    # Using check=True will raise CalledProcessError if typos are found (exit code 2)
    result = subprocess.run(['typos', 'temp_code.py'], capture_output=True, text=True, check=False)
    print(result.stdout)
    if result.returncode == 0:
        print("No typos found.")
    elif result.returncode == 2:
        print("Typos found (exit code 2).")
    else:
        print(f"Error during check: {result.stderr}")
except FileNotFoundError:
    print("Error: 'typos' command not found. Ensure it's installed and in your PATH.")

# 2. Fix typos in place
print("\n--- Fixing typos ---")
try:
    fix_result = subprocess.run(['typos', '--write-changes', 'temp_code.py'], capture_output=True, text=True, check=False)
    if fix_result.returncode == 0:
        print("Typos fixed successfully.")
    elif fix_result.returncode == 2:
        print("Typos fixed (some might remain if ambiguous).")
    else:
        print(f"Error during fix: {fix_result.stderr}")

    print("\n--- File content after fixing ---")
    with open("temp_code.py", "r") as f:
        fixed_content = f.read()
        print(fixed_content)

finally:
    # Clean up the dummy file
    if os.path.exists("temp_code.py"):
        os.remove("temp_code.py")

view raw JSON →