12

I use black for format normal .py files as well as Jupyter Notebook files (.ipynb). For notebooks, I want a shorter line-length.

Is it possible to specify different formatting rules for different file extensions with black?

2
  • Do you use pyproject.toml to configure black? Or just CLI flags?
    – Alex Kosh
    Commented Apr 15, 2022 at 20:45
  • I'm a pyproject.toml hipster Commented Apr 16, 2022 at 17:21

1 Answer 1

12

You could create two separate files for .py and .ipynb files and run them separately

Some usefull flags from docs:

--config FILE Read configuration from FILE path.

--include TEXT A regular expression that matches files and directories that should be included on recursive searches.

So, to format multiple types of files, run something like:

python -m black --config pyproject.py.toml --include '*.py' src
python -m black --config pyproject.ipynb.toml --include '*.ipynb' src

Also you could specify include field inside toml files. It's in docs too:

[tool.black]
line-length = 88
target-version = ['py37']
include = '\.pyi?$'
3
  • 1
    Is it possible to specify an equivalent to both of those python -m black --config lines in a single toml file somehow? I understand these commands point to two different files, but it would be great if black could conditionally apply formatting rules based on the file extension (.py or .ipynb) without needing to change the command. Also, I should mention that I'm using the vscode Black extension, so I can apply formatting to a .py file or .ipynb cell with a keybinding.
    – Mark
    Commented Aug 9, 2023 at 13:15
  • > Also you could specify include field inside toml files. It's in docs too. How do you actually run Black in that scenario? Leaving off options causes it to complain about requiring an argument, whereas I thought it should be looking for configuration files.
    – bmitc
    Commented Feb 5 at 21:17
  • If you have "include" inside toml file, just run black without include flag, like so: python -m black --config pyproject.ipynb.toml src
    – Alex Kosh
    Commented Feb 6 at 10:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.