Black: The Uncompromising Code Formatter

repository·main·Indexed 12 days ago

https://github.com/psf/black

An opinionated Python code formatter that provides speed, determinism, and freedom from manual formatting. Black is primarily a command line tool that supports Python 3.10+ and PyPy 3.8+. It includes specialized support for Jupyter Notebooks via the `black[jupyter]` extra and provides guidance on integrating with tools like isort, Flake8, and Pylint.

Tokens
22.1K
Snippets
86
Records
131
Agent score
97%

What's inside Black

  1. Available Black integration guides

    main

    Black provides official integration documentation for the following areas:

    • Editor / IDE: Setting up Black within your development environment.
    • GitHub Actions: Automating formatting within CI/CD pipelines.
    • Source version control: Integrating with tools like git.
    • Doctest formatting: Ensuring doctests are formatted according to Black's style.
  2. Integrate Black with PyCharm/IntelliJ IDEA

    main

    There are four primary ways to use Black in PyCharm/IntelliJ IDEA:

    1. Built-in Integration (PyCharm 2023.2+): The simplest method.
    2. Local Server: Uses the BlackConnect plugin and blackd for the fastest formatting by avoiding startup costs.
    3. External Tool: Manually configuring Black as an external process.
    4. File Watcher: Using the File Watchers plugin to trigger Black on file changes.
  3. How _Black_ handles empty lines

    main

    Black avoids spurious vertical whitespace to follow PEP 8 principles.

    • Inside functions: Single empty lines are allowed.
    • Module level: Single and double empty lines are allowed (unless they are within parenthesized expressions, in which case they are removed).
    • Function/Class definitions: Black inserts proper spacing: one line before/after inner functions, and two lines before/after module-level functions or classes. It does not insert empty lines between a definition and its preceding standalone comment.
    • Docstrings: Enforces a single empty line between a class-level docstring and the first following field or method (per PEP 257).
  4. How to ignore sections in Black

    main

    You can prevent Black from reformatting specific lines or blocks of code using special comments:

    • Single lines: Add # fmt: skip to a line. This can be combined with other comments (e.g., # fmt: skip # pylint # noqa) or used as a semicolon-separated list (e.g., # fmt: skip; pylint; noqa).
    • Code blocks: Wrap code with # fmt: off at the start and # fmt: on at the end. These must be at the same indentation level and within the same block (no unindenting between them).

    Black also supports YAPF's block comment style for compatibility.

  5. Improved overload groups in stub files (.pyi)

    main

    In .pyi stub files, the --preview style improves heuristics for blank lines around decorated function groups (like @overload).

    Rules applied to groups of $\ge 2$ decorated functions with the same name:

    1. Before the group: A blank line is inserted unless the preceding statement is a same-name decorated function or it is the first statement in the block.
    2. After the group: A blank line is inserted unless the following statement is a same-name decorated function.

    This ensures @overload groups are kept together without unwanted blank lines inside the group, even if one overload has a docstring.

    # Before
    @overload
    def foo(x: int) -> int:
        """Docs."""
    
    @overload                    # unwanted blank line within group
    def foo(x: str) -> str: ...
    def bar(x): ...              # no blank line after group
    
    # After (with --preview)
    @overload
    def foo(x: int) -> int:
        """Docs."""
    @overload
    def foo(x: str) -> str: ...
    
    def bar(x): ...
  6. String prefix normalization and r-strings

    main
    Black normalizes string quotes and string prefixes to lowercase. However, it makes an exception for r-strings (raw strings) to preserve compatibility with syntax highlighters like MagicPython (used by GitHub and VS Code). This ensures that r"string" is highlighted as a regular expression while R"string" is treated as a true raw string.
  7. Enable the string_processing unstable feature

    main

    The string_processing feature improves how long and short strings are handled:

    • Splits long string literals and merges short ones using parentheses.
    • Converts parts of f-strings that don't require formatting into plain strings when split.
    • Converts line continuation backslashes into parenthesized strings.
    • Strips unnecessary parentheses.

    Note: f-strings are not merged if doing so would change their internal quotation mark style.

  8. How _Black_ handles trailing commas

    main

    Black adds trailing commas to expressions that are split by commas where each element is on its own line (including function signatures).

    Exceptions and Behaviors:

    • Function signatures with *, *args, or **kwargs: Black only adds trailing commas if it detects the file is Python 3.6+ (by looking for f-strings or existing trailing commas in starred signatures). If you manually add a trailing comma in these cases and Black doesn't recognize it as safe, it will preserve your manual comma.
    • Manual Trigger: A pre-existing trailing comma informs Black to always 'explode' the contents of the current bracket pair into one item per line.
  9. How _Black_ formats strings

    main

    Black prefers double quotes (" and """) over single quotes (' and ''') to reduce reader distraction and align with PEP 257.

    String Normalization Rules

    • Quotes: Replaces single quotes with double quotes unless it increases the number of backslash escapes.
    • Prefixes: Standardizes prefixes to lowercase (e.g., r for raw), except for the capital R prefix. Unicode markers (u) are removed. For multiple characters, r is placed first (e.g., rf"string").
    • Escape Sequences: Normalizes escape sequences to lowercase (e.g., \uabcd), but uses uppercase for \N named character escapes.

    Adoption Helper

    If you are adopting Black in a project with existing single-quote conventions, use the --skip-string-normalization flag to prevent mass changes. This is recommended for adoption only, not for new projects.

    Docstrings

    Black corrects indentation for both quotations and text, removes superfluous trailing whitespace, and removes unnecessary newlines at the end of the docstring. It converts leading tabs to spaces but preserves tabs inside the text.

    black --skip-string-normalization .
  10. How _Black_ wraps lines

    main

    Black applies uniform horizontal and vertical whitespace by ignoring previous formatting.

    Horizontal Whitespace

    Rules follow pycodestyle recommendations.

    Vertical Whitespace

    Black attempts to render one full expression or simple statement per line.

    • If it fits the line length: It stays on one line.
    • If it exceeds the line length: Black looks at the first outer matching brackets and puts the contents on a separate indented line. If it still doesn't fit, it decomposes the expression further, indenting matching brackets at each level.
    • Comma-separated contents: For argument lists, dict literals, etc., Black first tries to keep them on the same line with matching brackets. If that fails, it puts every element on its own line.
    • Data structures and imports: If a data structure literal (tuple, list, set, dict) or a from ... import ... line cannot fit the allotted length, it is always split into one element per line. This minimizes git diffs and improves readability.
    # in:
    
    ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
    
    # out:
    
    ImportantClass.important_method(
        exc, limit, lookup_lines, capture_locals, extra_argument
    )
  11. How _Black_ handles binary operators and line breaks

    main

    Black breaks a line before a binary operator when splitting a block of code over multiple lines to comply with PEP 8.

    Operator Spacing

    • Most operators: Surrounded by single spaces.
    • Exceptions (No whitespace):
      • Unary operators (+, -, ~).
      • Power operators (**) when both operands are 'simple' (a NAME, numeric CONSTANT, or attribute access, with or without a preceding unary operator).

    Examples of no whitespace:

    a = x**y
    b = config.base**5.2
    c = 2**5

    Examples with whitespace:

    f = 2 ** get_exponent()
    g = get_x() ** get_y()