Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python code formatters rewrite source files in one consistent style. These libraries format code on save or in a pre-commit hook so that review diffs show changes in behavior rather than style.
Popularity
Ruff has the most installs and the most GitHub stars.
Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.
Libraries and code examples
Ruff
Ruff's formatter is a Python code formatter that runs as ruff format, a subcommand of the Ruff linter. The formatter is a drop-in replacement for Black. On large Black-formatted projects such as Django and Zulip, nearly every line comes out identical. Unlike Black, Ruff lets a project set the quote style, the indent style, and line endings. With docstring-code-format turned on, the formatter also reformats code examples inside docstrings. The --check flag lists unformatted files and exits with an error status, leaving the files unchanged.
Downloads / mo
428.0M
Stars
51.3K
Last release
0.17.5
License
MIT
Strengths
Formats docstring examples.Turn on docstring code formatting to format the Python examples inside docstrings.
Formats notebooks natively.Run ruff format on Jupyter notebooks without a separate wrapper.
Limitations
No import sorting.The formatter leaves import order alone. Sorting imports takes the linter's import rules first, with ruff check --select I --fix.
Not interchangeable with Black.Ruff differs from Black in a few deliberate ways. A project uses one of the two formatters for all its files.
Black is a Python code formatter with almost no style settings. A project that adopts Black gives up control over formatting details. In return, every Black-formatted codebase looks alike. The black command takes files or directories and rewrites the code in place, keeping diffs as small as possible. Jupyter notebook support comes from installing the jupyter extra, as in pip install "black[jupyter]". Ruff follows Black's style closely as a drop-in replacement.
Downloads / mo
116.2M
Stars
42.2K
Last release
26.10.1
License
MIT
Strengths
Checks the code still matches.After formatting, Black confirms the AST is unchanged. The --fast flag skips this check.
Formats Jupyter notebooks.Pass --ipynb to format any input as a notebook, such as code piped on standard input.
Limitations
Few settings.Choices such as quote style and indent style are fixed. Ruff lets a project configure both.
def _build_separate_module(self, elements: list, module_name: str,
module_dir: str) -> None:
"""
Constructs and writes the Python representation of a specific model
module, when the split_views=True in the read_vensim function.
Parameters
---------- elements: list
Elements belonging to the module module_name.
module_name: str
Name of the module
module_dir: str
Path of the directory where module files will be stored.
Returns
------- None
"""
text = textwrap.dedent('''
"""
Module %(module_name)s
Translated using PySD version %(version)s
"""
''' % {
"module_name": ".".join(module_name.parts[1:]),
"version": __version__,
})
funcs = self._generate_functions(elements)
text += funcs
text = black.format_file_contents(
text, fast=True, mode=black.FileMode())
outfile_name = module_dir / module_name.with_suffix(".py")
with outfile_name.open("w", encoding="UTF-8") as out:
out.write(text)
isort
isort sorts Python imports alphabetically and separates them into sections for the standard library, third-party packages, and project modules. The isort command rewrites files in place. With --diff, the command prints the proposed changes instead of applying them. From Python, isort.code returns a copy of a source string with the imports sorted. A black profile makes isort wrap long imports the way Black does. With that profile set, the two tools agree on import layout.
Downloads / mo
98.7M
Stars
7.0K
Last release
9.0.2
License
MIT
Strengths
Sorts imports in a string.Call isort.code with source text to get it back with imports sorted.
Works alongside Black.Set the isort profile to black, and the two tools agree on import layout.
Limitations
Imports only.Black or Ruff formats the rest of each file.
Atomic mode off.The --atomic flag skips changes that would introduce syntax errors. The flag is off by default because it stops isort from running on code written for a different Python version.
def format_python_code(code: str, library: str) -> str:
# Choose formatter based on the specified library if library == "black":
# Format code using Black with default settings formatted_code: str = black.format_str(code, mode=black.FileMode())
elif library == "autopep8":
# Format code using autopep8 formatted_code = autopep8.fix_code(code)
elif library == "yapf":
# Format code using yapf; returns (formatted_code, changed_flag) formatted_code, _ = yapf.yapf_api.FormatCode(code)
elif library == "ruff":
# Format code using a custom wrapper for Ruff (assumes string input/output) formatted_code = format_ruff_python(code)
else:
# Raise a ValueError for unrecognized formatter names raise ValueError(
f"[PYTHON-CODE-FORMATTING] Unknown formatting library selected: {library}"
)
# Sort and format imports using isort with Black compatibility formatted_code = isort.code(formatted_code, config=isort.Config(profile="black"))
return formatted_code
autopep8
autopep8 rewrites Python code to fix the style problems that pycodestyle, a Python style checker, reports when code breaks the official Python style guide. By default, the fixes change only whitespace. Each --aggressive flag allows further fixes, such as replacing x == None with x is None. From Python, the fix_code function takes a string of source and returns the fixed string. Unlike Black, which reformats every line in its own style, autopep8 changes only the lines pycodestyle flags.
Downloads / mo
8.2M
Stars
4.7K
Last release
2.3.2
License
MIT License
Strengths
Fixes selected rules.Pass --select or --ignore with pycodestyle codes to choose which fixes run.
Formats code strings.Call autopep8.fix_code() on a string of source code.
Limitations
Behavior-changing fixes.Changing x == None to x is None changes behavior when a class overrides __eq__. Fixes of that kind run only with --aggressive.
Some reports stay unfixed.Bad indentation that breaks syntax, and comments that look like code, are left for a person to fix.
def autopep8_fix_code_cell(source, options=None, apply_config=None):
"""
Applies autopep8.fix_code and takes care of newline characters.
autopep8.fix_code automatically adds a final newline at the end,
e.g. ``autopep8.fix_code('a=1')`` yields 'a = 1\\n'.
Note that this is not related to the 'W292' flag, i.e.
``autopep8.fix_code('a=1', options=dict(ignore=('W292',)))`` gives
the same result.
For notebook code cells, this behaviour does not make sense, hence
newline is removed if ``source`` does not end with one.
"""
source_corrected = autopep8.fix_code(source,
apply_config=apply_config,
options=options)
if not source.endswith('\n'):
return source_corrected[:-1]
return source_corrected
YAPF
YAPF is a Python formatter derived from clang-format. For each piece of code, the algorithm computes the layout that best fits the configured style. That style starts from a predefined one, such as Google's, with individual settings in a .style.yapf file or pyproject.toml. Two calls make up the library API. FormatCode formats a string of code, while FormatFile reads and formats a file. Both accept a lines argument that limits formatting to chosen line ranges, the way editors format a selection. YAPF exposes dozens of style settings, compared with the handful in Black.
Downloads / mo
5.7M
Stars
14.0K
Last release
0.43.0
License
Apache Software License
Strengths
Many style settings.Tune individual formatting knobs; the style.py module lists every one.
Formats chosen lines.Pass a lines argument to format a snippet instead of the whole file, as editors do.
Limitations
Newer syntax missing.Type parameter syntax and the formalized f-string grammar from recent Python releases aren't supported yet.
Large data literals.Large data literals can come out badly formatted. The README suggests wrapping them in # yapf: disable and # yapf: enable comments.
Beta releases.The README describes YAPF as beta. Released versions may change often.
def get_style_config(document_path, options=None):
# Exclude file if it follows the patterns for that exclude_patterns_from_ignore_file = file_resources.GetExcludePatternsForDir(
os.getcwd()
)
if file_resources.IsIgnored(document_path, exclude_patterns_from_ignore_file):
return []
# Get the default styles as a string # for a preset configuration, i.e. "pep8" style_config = file_resources.GetDefaultStyleForDir(os.path.dirname(document_path))
if options is None:
return style_config
# We have options passed from LSP format request # let's pass them to the formatter. # First we want to get a dictionary of the preset style # to pass instead of a string so that we can modify it style_config = style.CreateStyleFromConfig(style_config)
use_tabs = style_config["USE_TABS"]
indent_width = style_config["INDENT_WIDTH"]
if options.get("tabSize") is not None:
indent_width = max(int(options.get("tabSize")), 1)
if options.get("insertSpaces") is not None:
# TODO is it guaranteed to be a boolean, or can it be a string? use_tabs = not options.get("insertSpaces")
if use_tabs:
# Indent width doesn't make sense when using tabs # the specifications state: "Size of a tab in spaces" indent_width = 1
style_config["USE_TABS"] = use_tabs
style_config["INDENT_WIDTH"] = indent_width
style_config["CONTINUATION_INDENT_WIDTH"] = indent_width
for style_option, value in options.items():
# Apply arbitrary options passed as formatter options if style_option not in style_config:
# ignore if it's not a known yapf config continue
style_config[style_option] = value
return style_config
FAQ
Use Ruff for a new project. It formats and lints in one tool, and its formatter is a drop-in replacement for Black. Keep Black in projects that already run it, and add isort with the Black profile to sort imports.
Both give nearly the same output, because Ruff's formatter is a drop-in replacement for Black, but it differs in a few deliberate ways, so pick one and don't alternate. Ruff also lints in the same tool, and its formatter doesn't sort imports, so run ruff check --select I --fix before ruff format.
Run ruff format to format every Python file in the current directory. In CI, add --check to fail on unformatted files without writing any changes.
Use Black to reformat whole files in one opinionated style. Use autopep8 to fix only the problems pycodestyle reports: by default it changes whitespace and leaves the rest of the layout as written.
Use Black for one fixed style with little to configure. Choose YAPF to match a custom house style through its many style settings, but its last release was in Nov 2024, and it doesn't support some newer Python syntax yet.
For coding agents
Found your code formatter library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.