When you first learn Python, the question is whether the code runs. Once you maintain a project, different questions crop up. Why does everyone use different indentation, quotes, and line breaks? How should imports be arranged? Can we catch type errors and failing tests before committing?
These notes started with “How does Black format code?” and “How do I use isort?” We'll look at the role of each tool in development, then combine them into a working routine.
What problem does each part solve?
| Stage | Tool or file | Purpose |
|---|---|---|
| Environment isolation | venv | Install dependencies separately for each project. |
| Dependency installation | pip, dependency manifest | Install runtime and development packages into the environment. |
| Code formatting | Black | Standardize spaces, line breaks, quotes, and other layout. |
| Import organization | isort | Group, sort, and format import statements. |
| Static rule checking | Ruff or another linter | Find unused imports, undefined names, and similar issues. |
| Type checking | Mypy | Use annotations to check that arguments, return values, and other types match. |
| Automated testing | pytest | Run tests to verify behavior. |
| Shared configuration | pyproject.toml | Store project-level settings for the tools. |
| Commit-time checks | pre-commit | Run selected tools automatically at commit time. |
| Continuous integration | CI | Run project checks in a common environment. |
You can add these stages gradually. For a small project, isolation, formatting, and testing already go a long way. The examples use Python 3.11. Black and isort are pinned for the demonstration; those pins aren't a claim about what will always be the latest versions.
1. Install the tools in the project environment
Create a virtual environment in the project root:
python -m venv .venv
Activate it in a typical macOS or Linux shell:
source .venv/bin/activate
In Windows PowerShell use:
.venv\Scripts\Activate.ps1
Once it's active, install the tools:
python -m pip install black==25.1.0 isort==6.0.1
python -m pip runs the pip belonging to the current python. By default, a virtual environment isolates project packages from the base Python environment. Put .venv/ in .gitignore; share the dependency manifest and configuration. For more on environment management, see Using requirements.txt and virtual environments. Python venv documentation
2. Black: consistent code layout
Suppose example.py contains this code:
def example( x ,y ):
if x > y :
return x
else :
return y
Run:
black example.py
Black edits the file in place. The result is:
def example(x, y):
if x > y:
return x
else:
return y
The layout is consistent, and the original conditional logic remains. In practice, these are some of the most common commands:
# 格式化一个文件
black example.py
# 格式化目录,递归查找符合规则的文件
black your_folder/
# 格式化当前项目
black .
# 只展示差异,不修改文件
black --diff example.py
# 只检查,不修改文件
black --check .
# 检查,并展示具体差异
black --check --diff .
--check and --diff serve different purposes. --check reports the result through an exit code: 0 when no changes are needed, 1 when formatting is needed, and 123 on an internal error. It doesn't show line-by-line differences on its own. Add --diff to see those too. CI usually uses check mode. Black command-line documentation
Configure line length and string handling
Create pyproject.toml in the project root:
[tool.black]
line-length = 88
target-version = ["py311"]
88 is Black's default target line length. It's not a guarantee that every line will fit. Strings or comments that can't reasonably be split can still be longer after formatting.
Black normally prefers double quotes, while considering whether the change would introduce escapes. To preserve existing string quote styles, add this under the existing [tool.black] section:
skip-string-normalization = true
This skips normalization of string quotes and prefixes. It doesn't force single quotes. If you have no established style constraints, the defaults are fine. Black code style
3. isort: organize imports
Black doesn't group or sort imports. That's what isort does. Suppose the imports are mixed together like this:
import requests
import sys
from pathlib import Path
import os
After isort, standard-library and third-party imports are grouped:
import os
import sys
from pathlib import Path
import requests
Typical sections include __future__ imports, the standard library, third-party libraries, project modules, and relative imports. You can adjust classification in configuration. Here requests only demonstrates the third-party group; you don't have to execute the code to sort it. isort configuration options
The basic commands resemble Black's:
# 整理文件或目录,直接修改文件
isort example.py
isort your_folder/
isort .
# 只查看差异
isort --diff example.py
# 只检查,并输出差异
isort --check-only --diff .
A failed check returns a nonzero exit code, so scripts and CI can detect it. We use the full --check-only option here to make the intent clear. isort CLI documentation
Why set profile = "black"?
isort also decides how to wrap long imports, place parentheses, and handle trailing commas. If its settings disagree with Black, the two tools can keep rewriting the same section of code.
Append this configuration to the same pyproject.toml:
[tool.isort]
profile = "black"
line_length = 88
profile = "black" selects import formatting rules compatible with Black. It doesn't make isort use “Black's import sorting rules.” Black doesn't sort imports in the first place. If you change Black's line length, update isort's line_length too. Note that the two tools use a hyphen and an underscore respectively in their configuration keys. isort compatibility with Black
If a library lands in the wrong group, add settings under [tool.isort]:
known_first_party = ["myapp"]
known_third_party = ["requests", "numpy"]
Replace myapp with your package name. known_third_party marks modules as third-party; it doesn't order those libraries according to the list. isort configuration options
When using both tools, organize imports first and format the code second:
isort .
black .
For a one-off file without a configuration file, run isort --profile black example.py followed by Black. Using Black with other tools
4. Once the formatting is clean, what else needs checking?
This code is formatted perfectly well, but the call passes an argument of the wrong type:
def add(a: int, b: int) -> int:
return a + b
add("1", 2)
Passing Black and isort doesn't mean that error has been checked.
Mypy: check type relationships
python -m pip install mypy
mypy example.py
Save the example as example.py. From the annotations, Mypy can tell that the first argument should be an int. It performs static analysis without executing the call. Its checks depend on available type information, however. Under the defaults, unannotated functions don't receive the same level of checking. Getting started with Mypy
pytest: check behavior
Matching types don't prove that a calculation returns the right answer either. Suppose the project's app.py contains:
def add(a: int, b: int) -> int:
return a + b
Create test_app.py at the project root:
from app import add
def test_add() -> None:
assert add(1, 2) == 3
assert add(-1, 1) == 0
Install and run:
python -m pip install pytest
python -m pytest
pytest discovers and runs tests matching its naming conventions. If the implementation accidentally says return a - b, the types can still be correct but this test fails. As the project grows, put tests in a tests/ directory and add boundary cases and failure paths. Getting started with pytest
5. Where does Ruff fit?
Ruff includes both a linter and a formatter with separate entry points. ruff check runs static rules, while ruff format handles layout. Import organization belongs to the linter's I rules. This distinction helps identify overlapping responsibilities. Ruff linter documentation
One option is to keep Black and isort, then use Ruff to check other issues:
[tool.ruff]
target-version = "py311"
line-length = 88
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F"]
python -m pip install ruff
ruff check .
Here I is disabled. isort still sorts imports and Black still formats code. These Ruff rules find issues such as unused imports and undefined names. An ordinary ruff check reports problems. Add --fix to apply automatic fixes where available. Ruff rule selection and fixes
Another option is to have Ruff handle checks, import organization, and formatting. Change the existing select setting above to:
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]
Don't declare [tool.ruff.lint] twice in the same TOML file. Then run:
ruff check --fix .
ruff format .
Update your editor and commit hooks accordingly so there's one tool responsible for each of import sorting and formatting. Running ruff format alone doesn't organize imports. Ruff's formatting is close to Black's but not identical. Inspect the actual diff when switching. Mypy and pytest still handle type checking and tests. Ruff formatter documentation
6. Run Black and isort automatically with pre-commit
We'll continue with Black and isort. Install pre-commit:
python -m pip install pre-commit
Create .pre-commit-config.yaml at the root of the Git repository:
repos:
- repo: https://github.com/PyCQA/isort
rev: 6.0.1
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 25.1.0
hooks:
- id: black
This uses the compatible settings in pyproject.toml above and still runs isort before Black. The top-level repos: is required. A rev must name a tag or commit that actually exists in that repository; don't assume you can prefix a version with v. You can find the example versions on the isort release page and Black release page.
Install the hooks and check all tracked files first:
pre-commit install
pre-commit run --all-files
pre-commit creates independent environments for these hooks and downloads their dependencies on the first run. Subsequent commits usually check the applicable files staged for that commit. If a hook modifies a file, the commit is stopped. Review the diff, stage the changes again, and commit. Each developer needs to install the hooks in their own clone. pre-commit usage
7. From personal commands to a team workflow
pyproject.toml can hold tool settings in one place, and can also declare project metadata, dependencies, and build configuration. Merely adding [tool.black] or [tool.isort] doesn't install the tools or produce a dependency lock. Dependency manifests, lockfiles, and tool configuration each serve a different purpose. Python packaging configuration guide
For the demonstration project, record the development dependencies in requirements-dev.txt:
black==25.1.0
isort==6.0.1
ruff
mypy
pytest
pre-commit
python -m pip install -r requirements-dev.txt
This is a starter list. Only Black and isort are pinned, and their versions match the hooks. For a production project, pin the remaining tools and resolved dependencies as well. Record the verified versions for local development and CI.
With Black and isort, and Ruff checking only the non-import-sorting rules mentioned earlier, the local workflow can be:
isort .
black .
ruff check .
mypy app.py
python -m pytest
In CI, after installing the project and development dependencies, run the checks without changing files:
isort --check-only --diff .
black --check --diff .
ruff check .
mypy app.py
python -m pytest
Here app.py refers to the earlier demo file. Substitute your actual package directory. In CI, any failed command should fail the check. Use separate steps or a shell that stops on errors, for example. Editors can run the same formatting tools on save. Agreeing on tool versions and configuration reduces “passes locally, fails in CI” differences.
A toolchain puts repetitive checks into the team's daily routine. Code is organized on save or commit, CI runs consistent checks, and review can focus more on interface design and business logic.
Further reading and source notes
- Using requirements.txt and virtual environments covers dependency installation and environment selection in more detail.
- The later Python Project Setup Best Practices extends this to project configuration, Docker, testing, and CI.
This article is dated September 4, 2025 at 15:44 (+0800), the time of the original discussion. Official documentation links were checked during editing on November 13, 2026. Rolling documentation will continue to change. The example pins are neither a claim about today's latest releases nor evidence that the original discussion used those exact versions.