### Start blackd HTTP Server Source: https://context7.com/psf/black/llms.txt Install `blackd` with `pip install "black[d]"` and start the server using the `blackd` command. Options include specifying the port, allowing CORS, and increasing the maximum request body size. ```sh # Install blackd (requires aiohttp) pip install "black[d]" # Start on default port 45484 blackd # Start on a custom port blackd --bind-port 9090 # Allow browser-based clients from a specific origin blackd --cors-allow-origin http://localhost:3000 # Increase maximum request body size (default 5 MiB) blackd --max-body-size 10485760 ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://context7.com/psf/black/llms.txt Install `pre-commit` using pip and then set up the Git hooks with `pre-commit install`. Run all configured hooks on your repository files using `pre-commit run --all-files`. ```sh # Install and run pip install pre-commit pre-commit install pre-commit run --all-files ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/psf/black/blob/main/docs/contributing/the_basics.md Set up a virtual environment and install Black's development dependencies, including pre-commit hooks. ```console python3 -m venv .venv source .venv/bin/activate # activation for linux and mac .venv\Scripts\activate # activation for windows (.venv)$ pip install --group dev (.venv)$ pip install -e ".[d]" (.venv)$ pre-commit install ``` -------------------------------- ### Install Docs Dependencies and Build Docs Source: https://github.com/psf/black/blob/main/docs/contributing/the_basics.md Install necessary documentation dependencies and build the documentation locally to test changes. Ensure you are in the project's virtual environment. ```console (.venv)$ pip install --group docs (.venv)$ pip install -e ".[d]" (.venv)$ sphinx-build -a -b html -W docs/ docs/_build/ ``` -------------------------------- ### Install and Format Jupyter Notebooks Source: https://context7.com/psf/black/llms.txt Install Black with Jupyter support and format `.ipynb` files. Use the `black` command with the notebook file or directory. ```sh # Install pip install "black[jupyter]" # Format a single notebook black notebook.ipynb # Format all notebooks in a directory black notebooks/ # Check mode black --check notebook.ipynb # Pipe notebook via stdin cat notebook.ipynb | black --ipynb - # Register custom cell magics as Python code black --python-cell-magics writefile --python-cell-magics my_magic notebook.ipynb ``` -------------------------------- ### Install Black Source: https://github.com/psf/black/blob/main/README.md Install Black using pip. For Jupyter Notebook support, install with the 'jupyter' extra. ```sh pip install black ``` ```sh pip install "black[jupyter]" ``` -------------------------------- ### isort configuration examples for Black compatibility Source: https://github.com/psf/black/blob/main/docs/guides/using_black_with_other_tools.md Examples of isort configuration files demonstrating how to set the 'black' profile for compatibility with Black's code style. ```ini [settings] profile = black ``` ```ini [isort] profile = black ``` ```toml [tool.isort] profile = 'black' ``` ```ini [*.py] profile = black ``` -------------------------------- ### Install blackd Source: https://github.com/psf/black/blob/main/docs/usage_and_configuration/black_as_a_server.md Install blackd with its necessary dependencies using pip. ```shell pip install 'black[d]' ``` -------------------------------- ### Install Black with Jupyter Extra Source: https://github.com/psf/black/blob/main/docs/guides/using_black_with_jupyter_notebooks.md Install Black with the `jupyter` extra to enable formatting of `.ipynb` files. Without this extra, Black cannot format notebooks. ```sh pip install "black[jupyter]" ``` -------------------------------- ### Start blackd Server Source: https://github.com/psf/black/blob/main/docs/usage_and_configuration/black_as_a_server.md Start the blackd server on the default port, binding only to the local interface. It will print its version, host, and port. ```shell blackd --bind-port 9090 & # or let blackd choose a port ``` -------------------------------- ### Install Black with Vundle Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Install the Black plugin using Vundle. After adding the plugin, manually checkout the stable branch. ```vim Plugin 'psf/black' ``` ```sh cd ~/.vim/bundle/black git checkout origin/stable -b stable ``` -------------------------------- ### Install Black with 'd' extra for Local Server Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Install Black with the 'd' extra to enable the blackd server for faster formatting via the BlackConnect plugin. ```bash $ pip install 'black[d]' ``` -------------------------------- ### Install Black and Optional Features Source: https://context7.com/psf/black/llms.txt Install Black using pip. Use the `[jupyter]` extra for Jupyter Notebook support and `[d]` for the blackd HTTP server. Pipx is recommended for CLI tools. ```sh pip install black ``` ```sh pip install "black[jupyter]" ``` ```sh pip install "black[d]" ``` ```sh pipx install black ``` ```sh pip install git+https://github.com/psf/black ``` -------------------------------- ### Install Black with vim-plug (specific year tag) Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Pin the Black installation to a specific year's stable style using vim-plug and tag matching. ```vim Plug 'psf/black', { 'tag': '22.*.*' } ``` -------------------------------- ### Check Black Version Source: https://github.com/psf/black/blob/main/docs/usage_and_configuration/the_basics.md Use the --version flag to display the installed Black version. This is useful for verifying installation and compatibility. ```console $ black --version black, 26.3.1 ``` -------------------------------- ### Install Black with vim-plug (stable) Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Use this configuration with vim-plug to track the most recent stable version of Black. ```vim Plug 'psf/black', { 'branch': 'stable' } ``` -------------------------------- ### Get Help for Release Script Source: https://github.com/psf/black/blob/main/docs/contributing/release_process.md Use the --help flag to understand the available options for the release script. The script is tested with Python 3.12+. ```bash python3 scripts/release.py --help ``` -------------------------------- ### Install Black for Emacs/PyCharm/External Tool Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Install the Black package using pip. This is a prerequisite for most editor integrations. ```bash $ pip install black ``` -------------------------------- ### Install Black with vim-plug (latest tag) Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Configure vim-plug to use the latest tag matching a pattern, allowing for more control over version selection. ```vim Plug 'psf/black', { 'tag': '*.*.*' } ``` -------------------------------- ### Basic Black Pre-commit Configuration Source: https://github.com/psf/black/blob/main/docs/integrations/source_version_control.md Add this configuration to your `.pre-commit-config.yaml` to use Black as a pre-commit hook. Ensure pre-commit is installed. ```yaml repos: # Using this mirror lets us use mypyc-compiled black, which is about 2x faster - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.3.1 hooks: - id: black # It is recommended to specify the latest version of Python # supported by your project here, or alternatively use # pre-commit's default_language_version, see # https://pre-commit.com/#top_level-default_language_version language_version: python3.11 ``` -------------------------------- ### Verify Black Installation for Wing IDE Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Ensure that the Black executable is accessible from the command line. This is a prerequisite for Wing IDE integration. ```bash $ black --help ``` -------------------------------- ### Locate Black Installation (Windows) Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Find the installation path of the Black executable on Windows systems. This is useful for configuring external tools or file watchers. ```bash $ where black C:\Program Files\Python313\Scripts\black.exe # possible location ``` -------------------------------- ### Locate Black Installation (macOS/Linux/BSD) Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Find the installation path of the Black executable on macOS, Linux, or BSD systems. This is useful for configuring external tools or file watchers. ```bash $ which black /usr/local/bin/black # possible location ``` -------------------------------- ### Set up Gedit External Tool for Black Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Configure Gedit to run Black on the current document using an external tool script. Ensure Black is installed and accessible in your PATH. ```bash #!/bin/bash Name=$GEDIT_CURRENT_DOCUMENT_NAME black $Name ``` -------------------------------- ### Install Black using Vim 8 Native Package Management Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Manually install the Black plugin for Vim 8 by downloading the necessary files into the plugin directory. ```sh mkdir -p ~/.vim/pack/python/start/black/plugin mkdir -p ~/.vim/pack/python/start/black/autoload curl https://raw.githubusercontent.com/psf/black/stable/plugin/black.vim -o ~/.vim/pack/python/start/black/plugin/black.vim curl https://raw.githubusercontent.com/psf/black/stable/autoload/black.vim -o ~/.vim/pack/python/start/black/autoload/black.vim ``` -------------------------------- ### GitHub Actions for Jupyter Notebooks Source: https://context7.com/psf/black/llms.txt Enable Black to format Jupyter Notebooks by setting `jupyter: true`. This requires Black to be installed with the `jupyter` extra. ```yaml # Include Jupyter Notebooks - uses: psf/black@stable with: jupyter: true options: "--check" src: "." ``` -------------------------------- ### GitHub Actions with Options and Pinned Version Source: https://context7.com/psf/black/llms.txt Configure the Black GitHub Action with specific options and a version range. Ensure Black is installed with the specified version range using `version: "~= 26.0"`. ```yaml # With options and pinned version range - uses: psf/black@stable with: options: "--check --verbose" src: "./src" version: "~= 26.0" ``` -------------------------------- ### Check Black Version with Docker Source: https://github.com/psf/black/blob/main/docs/usage_and_configuration/black_docker_image.md Run this command to check the installed Black version within the Docker image. The `latest_release` tag is used here, but other tags can be substituted. ```bash docker run --rm pyfound/black:latest_release black --version ``` -------------------------------- ### blackd HTTP server Source: https://context7.com/psf/black/llms.txt blackd is a local HTTP server designed to reduce the startup overhead of Black, making it suitable for editor integrations. It can be installed via pip and started with various configuration options. ```APIDOC ## blackd HTTP server `blackd` is a local HTTP server that avoids the startup cost of spawning a new Black process per file. Useful for editor integrations. ```sh # Install blackd (requires aiohttp) pip install "black[d]" # Start on default port 45484 blackd # Start on a custom port blackd --bind-port 9090 # Allow browser-based clients from a specific origin blackd --cors-allow-origin http://localhost:3000 # Increase maximum request body size (default 5 MiB) blackd --max-body-size 10485760 ``` ``` -------------------------------- ### Configuration via `pyproject.toml` Source: https://context7.com/psf/black/llms.txt Black reads project-specific default options from the `[tool.black]` section in `pyproject.toml`. Command-line options always take precedence. ```APIDOC ## Configuration via `pyproject.toml` Black reads project-specific defaults from `[tool.black]` in `pyproject.toml`. Command-line options always take precedence. ```toml [tool.black] line-length = 88 target-version = ["py311", "py312"] required-version = "26" # Style options skip-string-normalization = false skip-magic-trailing-comma = false preview = false # File discovery include = '\.pyi?$' extend-exclude = ''' ( ^/foo.py # exclude a specific root-level file | .*_pb2\.py # exclude generated Protocol Buffer files | ^/migrations/ # exclude Django migrations ) ''' force-exclude = ''' ( ^/generated/ ) ' # Jupyter notebooks python-cell-magics = ["writefile", "my_custom_magic"] ``` ``` -------------------------------- ### Format Notebook from Standard Input Source: https://github.com/psf/black/blob/main/docs/guides/using_black_with_jupyter_notebooks.md Pipe notebook content to `black` via standard input and use the `--ipynb` flag to specify it's a Jupyter Notebook. ```sh cat notebook.ipynb | black --ipynb - ``` -------------------------------- ### Enable Unstable and Preview Features Source: https://context7.com/psf/black/llms.txt Use `--unstable` for experimental features or `--preview` with specific unstable features. Ensure you understand the risks associated with unstable features. ```sh $ black --unstable src/ ``` ```sh $ black --preview --enable-unstable-feature string_processing src/ ``` ```sh $ black --preview --enable-unstable-feature hug_parens_with_braces_and_square_brackets src/ ``` -------------------------------- ### Configuration via `pyproject.toml` Source: https://context7.com/psf/black/llms.txt Define project-specific Black defaults in `[tool.black]` within `pyproject.toml`. Command-line options always override these settings. ```toml [tool.black] line-length = 88 target-version = ["py311", "py312"] required-version = "26" # Style options skip-string-normalization = false skip-magic-trailing-comma = false preview = false # File discovery include = '\.pyi?$' extend-exclude = ''' ( ^/foo.py # exclude a specific root-level file | .*_pb2\.py # exclude generated Protocol Buffer files | ^/migrations/ # exclude Django migrations ) ''' force-exclude = ''' ( ^/generated/ ) # Jupyter notebooks python-cell-magics = ["writefile", "my_custom_magic"] ``` -------------------------------- ### Include Files and Directories Source: https://github.com/psf/black/blob/main/docs/usage_and_configuration/the_basics.md The --include option uses a regular expression to specify which files and directories should be included in recursive searches. This overrides all exclusions. Default inclusions are '.pyi' and '.ipynb'. ```console ['.pyi', '.ipynb'] ``` -------------------------------- ### Basic Black Usage Source: https://github.com/psf/black/blob/main/docs/getting_started.md Run Black with sensible defaults to format your source files or directories. This is the most common way to apply Black formatting to your project. ```sh black {source_file_or_directory}... ``` -------------------------------- ### Disable Black virtualenv in Vim Source: https://github.com/psf/black/blob/main/docs/integrations/editors.md Configure Vim to use the system installation of Black instead of a virtual environment by setting 'g:black_use_virtualenv' to 0. ```vim let g:black_use_virtualenv = 0 ``` -------------------------------- ### pycodestyle Configuration for Black Compatibility Source: https://context7.com/psf/black/llms.txt Configure `pycodestyle` (or `setup.cfg`) to match Black's 88-character line length and ignore specific codes like E203 and E701. ```ini # setup.cfg or .pycodestyle [pycodestyle] max-line-length = 88 ignore = E203,E701 ``` -------------------------------- ### Configure Black Version in GitHub Actions Source: https://github.com/psf/black/blob/main/docs/integrations/github_actions.md Configure the Black version to use in your GitHub Actions workflow. This example specifies a version using the compatible release operator. ```yaml - uses: psf/black@stable with: options: "--check --verbose" src: "./src" version: "~= 22.0" ``` -------------------------------- ### Format Doctests within Python Docstrings Source: https://github.com/psf/black/blob/main/docs/integrations/doctest_formatting.md This example shows how doctests within a Python docstring, marked with a Pycon code block, can be formatted by tools like blacken-docs. ```python def add_one(n: int) -> int: """ Examples -------- ```pycon >>> add_one(1) == 2 ``` """ return n + 1 ``` -------------------------------- ### Opt into Future Styles with Preview Source: https://context7.com/psf/black/llms.txt The `--preview` flag enables style changes planned for the next stable release. The `--unstable` flag includes changes with known issues. ```sh # Try next year's stable style $ black --preview src/ ``` -------------------------------- ### Basic pyproject.toml Configuration for Black Source: https://github.com/psf/black/blob/main/docs/usage_and_configuration/the_basics.md Configure basic Black settings like line length, target Python versions, and include/exclude patterns. Use single-quoted strings for regular expressions. ```toml [tool.black] line-length = 88 target-version = ['py37'] include = '\.pyi?$' # 'extend-exclude' excludes files or directories in addition to the defaults extend-exclude = ''' # A regex preceded with ^/ will apply only to files and directories # in the root of the project. ( ^/foo.py # exclude a file named foo.py in the root of the project | .*_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project ) ''' ``` -------------------------------- ### Pylint configuration in setup.cfg Source: https://github.com/psf/black/blob/main/docs/guides/using_black_with_other_tools.md Configure Pylint's maximum line length to 88 in the [pylint] section of setup.cfg. ```ini [pylint] max-line-length = 88 ``` -------------------------------- ### Pre-commit integration Source: https://context7.com/psf/black/llms.txt Integrate Black into your pre-commit hooks to automatically enforce code formatting before each commit. This example shows how to configure Black for standard Python files and Jupyter Notebooks. ```APIDOC ## Pre-commit integration Add Black to your pre-commit hooks so formatting is enforced before every commit. ```yaml # .pre-commit-config.yaml repos: # Use the mypyc-compiled mirror for ~2x speed improvement - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.3.1 hooks: - id: black language_version: python3.11 # For Jupyter Notebooks - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.3.1 hooks: - id: black-jupyter language_version: python3.11 # Exclude files via pre-commit (recommended over --exclude) - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.3.1 hooks: - id: black exclude: ^migrations/|^generated/ language_version: python3.11 ``` ```sh # Install and run pip install pre-commit pre-commit install pre-commit run --all-files ``` ``` -------------------------------- ### Format Doctests in Pycon Blocks (reStructuredText) Source: https://github.com/psf/black/blob/main/docs/integrations/doctest_formatting.md Use this for formatting doctests specifically within Pycon code blocks in reStructuredText files. This allows Black to format the interactive Python session examples. ```rst .. code-block:: pycon >>> print("Hello world!") ``` -------------------------------- ### Configure Black Pre-commit Hooks Source: https://context7.com/psf/black/llms.txt Integrate Black into your Git workflow by adding it to your `.pre-commit-config.yaml`. Use the `psf/black-pre-commit-mirror` repository and specify the `id: black` hook. You can also use `black-jupyter` for notebooks and exclude specific directories. ```yaml # .pre-commit-config.yaml repos: # Use the mypyc-compiled mirror for ~2x speed improvement - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.3.1 hooks: - id: black language_version: python3.11 # For Jupyter Notebooks - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.3.1 hooks: - id: black-jupyter language_version: python3.11 # Exclude files via pre-commit (recommended over --exclude) - repo: https://github.com/psf/black-pre-commit-mirror rev: 26.3.1 hooks: - id: black exclude: ^migrations/|^generated/ language_version: python3.11 ``` -------------------------------- ### Format Doctests in Pycon Blocks (Markdown) Source: https://github.com/psf/black/blob/main/docs/integrations/doctest_formatting.md Use this for formatting doctests specifically within Pycon code blocks in Markdown files. This allows Black to format the interactive Python session examples. ```markdown ```md ```python >>> print("Hello world!") ``` ``` ``` -------------------------------- ### Clone Black Repository Source: https://github.com/psf/black/blob/main/docs/contributing/the_basics.md Clone the Black repository to your local machine and navigate into the directory. ```console $ git clone https://github.com/psf/black.git $ cd black ``` -------------------------------- ### Run Black as a Package Source: https://github.com/psf/black/blob/main/docs/getting_started.md If running Black directly as a command doesn't work, you can execute it as a Python package. This ensures Black is run using the correct Python environment. ```sh python -m black {source_file_or_directory}... ``` -------------------------------- ### Programmatic Python API: `black.format_file_in_place` Source: https://context7.com/psf/black/llms.txt Formats a file directly on disk using `pathlib.Path`. It allows specifying target Python versions and line lengths, and can either write changes back to the file or just check if changes are needed. ```APIDOC ## Programmatic Python API: `black.format_file_in_place` Format a file on disk in place, using `pathlib.Path`. ```python from pathlib import Path import black path = Path("src/my_module.py") mode = black.Mode( target_versions={black.TargetVersion.PY311}, line_length=100, ) # WriteBack.YES writes in place; WriteBack.CHECK returns True if changes needed changed = black.format_file_in_place( path, fast=False, mode=mode, write_back=black.WriteBack.YES, ) print(f"File changed: {changed}") ``` ```