Darker: Incremental Python Code Formatter

3.0.0 · active · verified Thu Apr 16

Darker (version 3.0.0) is a Python utility that applies code formatting (using tools like Black, Ruff, isort, Flynt, and pyupgrade) only to regions of Python files that have changed since the last Git commit. This allows for gradual style unification in existing projects without large, disruptive formatting commits. It is actively maintained with regular releases.

Common errors

Warnings

Install

Quickstart

To use Darker, navigate to your Git repository and run it on specific files or directories. This example demonstrates basic usage for formatting modified lines in a Python file and showing a diff. Ensure you have `darker` and its desired formatters (e.g., `black`) installed.

# First, ensure you have a Git repository initialized and a Python file with changes
# Example setup:
# mkdir my_project && cd my_project && git init
# echo "print ( 'Hello, world' )" > my_file.py
# git add my_file.py && git commit -m "Initial commit"
# echo "def foo ( ):\n    pass\nprint ( 'Another line' )" >> my_file.py

# Format only the modified lines in 'my_file.py'
# Requires black to be installed, e.g., pip install 'darker[black]'
import subprocess
import os

def run_darker(command):
    try:
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        print(result.stdout)
        if result.stderr:
            print(f"Stderr: {result.stderr}")
    except subprocess.CalledProcessError as e:
        print(f"Command failed with exit code {e.returncode}\nStdout: {e.stdout}\nStderr: {e.stderr}")

# Assuming you are in a git repository with changes in my_file.py
# This will reformat the added/modified lines in my_file.py
# For this example to be runnable, ensure 'darker' and 'black' are installed and a Git repo exists.
# To see an effect, modify my_file.py after an initial commit:
#   echo "def some_func (   ):\n    x  =   1" >> my_file.py
# then run `python -m darker my_file.py`

print("Running darker on 'my_file.py'...")
# Use python -m darker to ensure it runs from the correct environment
run_darker(['python', '-m', 'darker', 'my_file.py'])

print("\nShowing the diff without applying changes (dry run):")
run_darker(['python', '-m', 'darker', '--diff', 'my_file.py'])

print("\nApplying darker with isort on 'my_file.py' (if isort installed):")
run_darker(['python', '-m', 'darker', '--isort', 'my_file.py'])

view raw JSON →