Top Related Projects
flake8 is a python tool that glues together pycodestyle, pyflakes, mccabe, and third-party plugins to check the style and quality of some python code.
A formatter for Python files
A tool that automatically formats Python code to conform to the PEP 8 style guide.
It's not just a linter that annoys you!
An extremely fast Python linter and code formatter, written in Rust.
Quick Overview
Black is an opinionated Python code formatter that automatically formats Python code to conform to a consistent style. It aims to provide a deterministic output, reducing the need for debates about code style in teams and making code reviews more focused on content rather than formatting.
Pros
- Enforces a consistent code style across projects and teams
- Saves time by automating code formatting
- Improves code readability and maintainability
- Integrates well with popular editors and CI/CD pipelines
Cons
- Opinionated nature may not suit all coding preferences
- Can sometimes produce unexpected formatting results
- May require initial setup and configuration in projects
- Limited customization options compared to other formatters
Code Examples
- Basic usage:
# Before formatting
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# After formatting with Black
def long_function_name(
var_one, var_two, var_three, var_four
):
print(var_one)
- Handling string quotes:
# Before formatting
x = "hello"
y = 'world'
# After formatting with Black
x = "hello"
y = "world"
- Formatting imports:
# Before formatting
import sys, os
from collections import defaultdict, OrderedDict
# After formatting with Black
import os
import sys
from collections import OrderedDict, defaultdict
Getting Started
To use Black, first install it using pip:
pip install black
Then, to format a file or directory:
black path/to/file_or_directory
To integrate Black with your editor, refer to the documentation for specific instructions. For example, in VS Code, you can add the following to your settings.json
:
{
"python.formatting.provider": "black",
"editor.formatOnSave": true
}
This will automatically format your Python files using Black when you save them.
Competitor Comparisons
flake8 is a python tool that glues together pycodestyle, pyflakes, mccabe, and third-party plugins to check the style and quality of some python code.
Pros of flake8
- More flexible and customizable with various plugins
- Checks for logical errors and complexity in addition to style
- Faster execution time for large codebases
Cons of flake8
- Requires more configuration to achieve consistent results
- May produce false positives or miss some style issues
- Does not automatically format code, only reports issues
Code Comparison
flake8:
def example_function(param1, param2):
result = param1 + param2
return result
Black:
def example_function(param1, param2):
result = param1 + param2
return result
In this simple example, both tools would consider the code acceptable. However, Black would automatically format more complex code to adhere to its opinionated style, while flake8 would only report style violations without making changes.
flake8 focuses on identifying potential issues and style violations, while Black is an opinionated code formatter that automatically applies a consistent style. flake8 offers more flexibility and can catch logical errors, but requires more setup. Black, on the other hand, provides a simpler, "no-decisions" approach to code formatting but may be less customizable for specific project needs.
A formatter for Python files
Pros of YAPF
- More configurable, allowing fine-tuning of formatting style
- Supports multiple formatting styles (PEP8, Google, Chromium, Facebook)
- Can preserve existing formatting in some cases
Cons of YAPF
- Less opinionated, which can lead to inconsistencies across projects
- Slower performance compared to Black
- Configuration options can be overwhelming for new users
Code Comparison
YAPF:
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
Black:
def long_function_name(
var_one,
var_two,
var_three,
var_four,
):
print(var_one)
Both Black and YAPF are popular Python code formatters, but they have different philosophies. Black is more opinionated and aims for consistency across all projects, while YAPF offers more flexibility in formatting styles. Black generally produces more consistent results and is faster, but YAPF allows for more customization to match existing project styles. The choice between them often depends on project requirements and team preferences.
A tool that automatically formats Python code to conform to the PEP 8 style guide.
Pros of autopep8
- More configurable, allowing users to customize formatting rules
- Preserves existing code structure more closely
- Faster execution for large codebases
Cons of autopep8
- Less opinionated, which can lead to inconsistent formatting across projects
- Doesn't enforce a strict style guide, potentially allowing some PEP 8 violations
- May require more manual intervention to achieve consistent formatting
Code Comparison
autopep8:
def example_function(arg1, arg2,arg3):
result = arg1+arg2+arg3
return result
Black:
def example_function(arg1, arg2, arg3):
result = arg1 + arg2 + arg3
return result
Black applies more aggressive formatting, ensuring consistent spacing and line breaks. autopep8 makes minimal changes, preserving the original structure more closely.
Both tools aim to improve Python code formatting, but Black takes a more opinionated approach with fewer configuration options, while autopep8 offers more flexibility at the cost of potential inconsistencies. The choice between them depends on project requirements and team preferences for code style enforcement.
It's not just a linter that annoys you!
Pros of Pylint
- More comprehensive: Checks for a wider range of issues, including code style, errors, and potential bugs
- Highly configurable: Allows customization of rules and checks to fit specific project needs
- Provides a numerical code quality score, helping track improvements over time
Cons of Pylint
- Can be slower to run, especially on large codebases
- May produce more false positives, requiring careful configuration
- Has a steeper learning curve due to its extensive feature set
Code Comparison
Pylint example:
# pylint: disable=invalid-name
x = 5 # This variable name would normally trigger a warning
Black example:
def long_function_name(
parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6
):
print("Black will format this function signature")
Black focuses solely on code formatting, while Pylint performs a broader range of checks. Black automatically reformats code, whereas Pylint provides warnings and suggestions for improvement. Both tools serve different purposes in Python development workflows, with Black ensuring consistent formatting and Pylint helping maintain overall code quality and adherence to best practices.
An extremely fast Python linter and code formatter, written in Rust.
Pros of Ruff
- Significantly faster performance due to being written in Rust
- More comprehensive linting and formatting capabilities
- Combines multiple tools (linter, formatter, import sorter) into one
Cons of Ruff
- Newer project with potentially less stability and community support
- May have fewer customization options compared to Black's mature ecosystem
- Learning curve for users familiar with Black's simplicity
Code Comparison
Black:
def long_function_name(
var_one, var_two, var_three, var_four
):
print(var_one)
Ruff:
def long_function_name(
var_one,
var_two,
var_three,
var_four,
):
print(var_one)
Ruff's default formatting is similar to Black's, but with subtle differences like trailing commas in function definitions. Both tools aim for consistent, opinionated formatting, but Ruff offers additional linting capabilities beyond just formatting.
While Black focuses solely on code formatting, Ruff combines formatting, linting, and import sorting into a single tool. This integration can streamline the development process and potentially improve overall code quality. However, Black's simplicity and established presence in the Python ecosystem make it a reliable choice for projects prioritizing straightforward formatting.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
The Uncompromising Code Formatter
âAny color you like.â
Black is the uncompromising Python code formatter. By using it, you agree to cede
control over minutiae of hand-formatting. In return, Black gives you speed,
determinism, and freedom from pycodestyle
nagging about formatting. You will save time
and mental energy for more important matters.
Blackened code looks the same regardless of the project you're reading. Formatting becomes transparent after a while and you can focus on the content instead.
Black makes code review faster by producing the smallest diffs possible.
Try it out now using the Black Playground. Watch the PyCon 2019 talk to learn more.
Read the documentation on ReadTheDocs!
Installation and usage
Installation
Black can be installed by running pip install black
. It requires Python 3.8+ to run.
If you want to format Jupyter Notebooks, install with pip install "black[jupyter]"
.
If you can't wait for the latest hotness and want to install from GitHub, use:
pip install git+https://github.com/psf/black
Usage
To get started right away with sensible defaults:
black {source_file_or_directory}
You can run Black as a package if running it as a script doesn't work:
python -m black {source_file_or_directory}
Further information can be found in our docs:
Black is already successfully used by many projects, small and big. Black has a comprehensive test suite, with efficient parallel tests, and our own auto formatting and parallel Continuous Integration runner. Now that we have become stable, you should not expect large formatting changes in the future. Stylistic changes will mostly be responses to bug reports and support for new Python syntax. For more information please refer to The Black Code Style.
Also, as a safety measure which slows down processing, Black will check that the
reformatted code still produces a valid AST that is effectively equivalent to the
original (see the
Pragmatism
section for details). If you're feeling confident, use --fast
.
The Black code style
Black is a PEP 8 compliant opinionated formatter. Black reformats entire files in place. Style configuration options are deliberately limited and rarely added. It doesn't take previous formatting into account (see Pragmatism for exceptions).
Our documentation covers the current Black code style, but planned changes to it are also documented. They're both worth taking a look at:
Changes to the Black code style are bound by the Stability Policy:
Please refer to this document before submitting an issue. What seems like a bug might be intended behaviour.
Pragmatism
Early versions of Black used to be absolutist in some respects. They took after its initial author. This was fine at the time as it made the implementation simpler and there were not many users anyway. Not many edge cases were reported. As a mature tool, Black does make some exceptions to rules it otherwise holds.
Please refer to this document before submitting an issue just like with the document above. What seems like a bug might be intended behaviour.
Configuration
Black is able to read project-specific default values for its command line options
from a pyproject.toml
file. This is especially useful for specifying custom
--include
and --exclude
/--force-exclude
/--extend-exclude
patterns for your
project.
You can find more details in our documentation:
And if you're looking for more general configuration documentation:
Pro-tip: If you're asking yourself "Do I need to configure anything?" the answer is "No". Black is all about sensible defaults. Applying those defaults will have your code in compliance with many other Black formatted projects.
Used by
The following notable open-source projects trust Black with enforcing a consistent code style: pytest, tox, Pyramid, Django, Django Channels, Hypothesis, attrs, SQLAlchemy, Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv), pandas, Pillow, Twisted, LocalStack, every Datadog Agent Integration, Home Assistant, Zulip, Kedro, OpenOA, FLORIS, ORBIT, WOMBAT, and many more.
The following organizations use Black: Facebook, Dropbox, KeepTruckin, Lyft, Mozilla, Quora, Duolingo, QuantumBlack, Tesla, Archer Aviation.
Are we missing anyone? Let us know.
Testimonials
Mike Bayer, author of SQLAlchemy
:
I can't think of any single tool in my entire programming career that has given me a bigger productivity increase by its introduction. I can now do refactorings in about 1% of the keystrokes that it would have taken me previously when we had no way for code to format itself.
Dusty Phillips, writer:
Black is opinionated so you don't have to be.
Hynek Schlawack, creator of attrs
, core developer of
Twisted and CPython:
An auto-formatter that doesn't suck is all I want for Xmas!
Carl Meyer, Django core developer:
At least the name is good.
Kenneth Reitz, creator of requests
and pipenv
:
This vastly improves the formatting of our code. Thanks a ton!
Show your style
Use the badge in your project's README.md:
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
Using the badge in README.rst:
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
License
MIT
Contributing
Welcome! Happy to see you willing to make the project better. You can get started by reading this:
You can also take a look at the rest of the contributing docs or talk with the developers:
Change log
The log has become rather long. It moved to its own file.
See CHANGES.
Authors
The author list is quite long nowadays, so it lives in its own file.
See AUTHORS.md
Code of Conduct
Everyone participating in the Black project, and in particular in the issue tracker, pull requests, and social media activity, is expected to treat other people with respect and more generally to follow the guidelines articulated in the Python Community Code of Conduct.
At the same time, humor is encouraged. In fact, basic familiarity with Monty Python's Flying Circus is expected. We are not savages.
And if you really need to slap somebody, do it with a fish while dancing.
Top Related Projects
flake8 is a python tool that glues together pycodestyle, pyflakes, mccabe, and third-party plugins to check the style and quality of some python code.
A formatter for Python files
A tool that automatically formats Python code to conform to the PEP 8 style guide.
It's not just a linter that annoys you!
An extremely fast Python linter and code formatter, written in Rust.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot