Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change 88 characters limit for Black plugin in PyCharm

I am using Black inside PyCharm to format my Python code.

I am using the Black-Pycharm plugin, unfortunately, selecting code and applying Black on it (Code > Reformat Code (BLACK)) cuts all my lines at 88 characters (the default limit for Black).

I want to change this limit to cut the lines at 80 characters. I tried two different ways:

  1. Changing the Black exe path in the "Black plugin settings" from ~/.local/bin/black to ~/.local/bin/black -l80, but applying Black with PyCharm outputs this error: BlackPycharm: Cannot run program "/home/BCT/.local/bin/black -l80": error=2, File or folder not found

  2. Using Black as an 'External Tool' in Pycharm (as described here), and specifying the line length in the arguments text box. This successfully applies Black on my file with the desired character limit, but:

    • It automatically saves/replaces my file with the new formatted file, I can't undo the change.
    • I can't apply Black on a portion of code only.

Do you know ways to use Black with:

  • The ability to specify a desired line length
  • The ability to reformat only a portion of code

at the same time ?

EDIT: Apparently PyCharm cannot use Black for only a portion of code...

like image 680
Be Chiller Too Avatar asked Dec 10 '18 13:12

Be Chiller Too


2 Answers

I also had the same problem with adjusting the linelength for the black 'external tool'.

1- follow this link to install and set black as an external tool: https://black.readthedocs.io/en/stable/editor_integration.html#pycharm-intellij-idea

2- within the "PyCharm/IntelliJ IDEA" section, in "Arguments":

replace "$FilePath$" with "$FilePath$" -l 120

Note: the '-l 120' should be outside the quotes, and replace 120 by whatever line length you need.

Cheers!

Maher.

like image 73
Nadros Avatar answered Nov 06 '22 05:11

Nadros


I use Black as an external tool within PyCharm, but I am able to specify line length by adding a pyproject.toml (The PEP/ more info) file to my root project directory. I don't have to pass anything as an argument. Maybe it's able to solve your problems. It looks the following way:

# NOTE: you have to use single-quoted strings in TOML for regular expressions.
# It's the equivalent of r-strings in Python.  Multiline strings are treated as
# verbose regular expressions by Black.  Use [ ] to denote a significant space
# character.

[tool.black]
line-length = 79
target-version = ['py37', 'py38']
include = '\.pyi?$'
exclude = '''
/(
    \.eggs
  | \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist

  # The following are specific to Black, you probably don't want those.
  | blib2to3
  | tests/data
  | profiling
)/
'''
like image 39
Lars Gebraad Avatar answered Nov 06 '22 05:11

Lars Gebraad