You can use isort.hooks.git_hook within your .git/hooks/pre-commit script to automatically check or format Python imports before a commit is finalized.
Strict Mode (Fail on errors)
To prevent a commit if isort finds errors (strict mode), use the following configuration in your .git/hooks/pre-commit file:
#!/usr/bin/env python
import sys
from isort.hooks import git_hook
sys.exit(git_hook(strict=True, modify=True, lazy=True, settings_file=""))
Warning Mode (Allow commit despite errors)
- Display warnings only: Call
git_hook without the strict parameter. - Display warnings without fixing code: Call
git_hook without the modify parameter.
Argument Reference
strict: If True, the commit fails if imports are not correctly sorted.modify: If True, isort will automatically fix the files. If False, it only checks them.lazy: If True, it ensures all tracked files are properly isorted (useful for users who use git commit -a). If False or omitted, it only checks files currently added to the index.settings_file: The path to a specific configuration file. If empty (""), isort searches upward from the directory of the first staged file until a valid config is found.
#!/usr/bin/env python
import sys
from isort.hooks import git_hook
sys.exit(git_hook(strict=True, modify=True, lazy=True, settings_file=""))