The uncompromising code formatter.
npx @tessl/cli install tessl/pypi-black@25.1.00
# Black
1
2
Black is the uncompromising Python code formatter that formats Python code to be consistent and readable. It provides both command-line and programmatic APIs for formatting Python source code, Jupyter notebooks, and stub files according to configurable style rules.
3
4
## Package Information
5
6
- **Package Name**: black
7
- **Language**: Python
8
- **Installation**: `pip install black`
9
10
## Core Imports
11
12
```python
13
import black
14
```
15
16
Common imports for specific functionality:
17
18
```python
19
from black import format_str, format_file_in_place, Mode, TargetVersion
20
from black import WriteBack, Changed, Report, NothingChanged
21
```
22
23
## Basic Usage
24
25
```python
26
import black
27
28
# Format a string of Python code
29
code = """def hello( name ):
30
print(f'Hello {name}!')"""
31
32
# Format with default settings
33
formatted = black.format_str(code, mode=black.Mode())
34
print(formatted)
35
# Output: def hello(name):
36
# print(f"Hello {name}!")
37
38
# Format with custom line length
39
mode = black.Mode(line_length=79)
40
formatted = black.format_str(code, mode=mode)
41
42
# Format targeting specific Python versions
43
mode = black.Mode(target_versions={black.TargetVersion.PY39, black.TargetVersion.PY310})
44
formatted = black.format_str(code, mode=mode)
45
46
# Format file in place
47
from pathlib import Path
48
changed = black.format_file_in_place(
49
Path("script.py"),
50
fast=False,
51
mode=black.Mode(),
52
write_back=black.WriteBack.YES
53
)
54
```
55
56
## Architecture
57
58
Black's architecture centers around the Mode configuration system that controls all formatting behavior:
59
60
- **Mode**: Central configuration class that controls formatting options, target Python versions, and feature flags
61
- **Formatting Pipeline**: AST-based parsing and transformation with safety checks for equivalent output
62
- **Target Version System**: Automatic detection and enforcement of Python version compatibility
63
- **Preview Features**: Opt-in experimental formatting behaviors for future style evolution
64
- **Multi-format Support**: Unified handling of .py files, .pyi stub files, and .ipynb Jupyter notebooks
65
66
## Capabilities
67
68
### Core Formatting Functions
69
70
Primary API functions for formatting Python code as strings, file contents, and files in place. Includes AST safety validation and stable formatting verification.
71
72
```python { .api }
73
def format_str(src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = ()) -> str: ...
74
def format_file_contents(src_contents: str, *, fast: bool, mode: Mode, lines: Collection[tuple[int, int]] = ()) -> str: ...
75
def format_file_in_place(src: Path, fast: bool, mode: Mode, write_back: WriteBack = WriteBack.NO, lock: Any = None, *, lines: Collection[tuple[int, int]] = ()) -> bool: ...
76
```
77
78
[Core Formatting](./formatting.md)
79
80
### Configuration and Modes
81
82
Mode configuration system for controlling formatting behavior, target Python versions, preview features, and style options. Includes target version detection and feature compatibility checking.
83
84
```python { .api }
85
class Mode:
86
target_versions: set[TargetVersion] = field(default_factory=set)
87
line_length: int = 88
88
string_normalization: bool = True
89
is_pyi: bool = False
90
is_ipynb: bool = False
91
skip_source_first_line: bool = False
92
magic_trailing_comma: bool = True
93
python_cell_magics: set[str] = field(default_factory=set)
94
preview: bool = False
95
unstable: bool = False
96
enabled_features: set[Preview] = field(default_factory=set)
97
```
98
99
[Configuration and Modes](./configuration.md)
100
101
### Jupyter Notebook Support
102
103
Specialized formatting functions for Jupyter notebooks and individual notebook cells, with support for IPython magics and notebook-specific formatting rules.
104
105
```python { .api }
106
def format_cell(src: str, *, fast: bool, mode: Mode) -> str: ...
107
def format_ipynb_string(src_contents: str, *, fast: bool, mode: Mode) -> str: ...
108
```
109
110
[Jupyter Support](./jupyter.md)
111
112
### Command Line Interface
113
114
Complete CLI implementation with all formatting options, file discovery, configuration loading, and output modes including diffs and checks.
115
116
```python { .api }
117
def main(ctx: click.Context, **options) -> None: ...
118
def get_sources(*, root: Path, src: tuple[str, ...], quiet: bool, verbose: bool, include: Pattern[str], exclude: Optional[Pattern[str]], extend_exclude: Optional[Pattern[str]], force_exclude: Optional[Pattern[str]], report: Report, stdin_filename: Optional[str]) -> set[Path]: ...
119
```
120
121
[Command Line Interface](./cli.md)
122
123
### Server API (BlackD)
124
125
HTTP server API for formatting Python code via REST endpoints, with header-based configuration and protocol versioning.
126
127
```python { .api }
128
def main(bind_host: str, bind_port: int) -> None: ...
129
def make_app() -> web.Application: ...
130
def handle(request: web.Request, executor: Executor) -> web.Response: ...
131
```
132
133
[Server API](./server.md)
134
135
### Types and Exceptions
136
137
Exception classes for error handling, constants for default configuration, type definitions, and utility functions for encoding and feature detection.
138
139
```python { .api }
140
class NothingChanged(UserWarning): ...
141
class InvalidInput(ValueError): ...
142
class ASTSafetyError(Exception): ...
143
```
144
145
[Types and Exceptions](./types.md)