how to auto format E501 line too long (89 > 88 characters) in pre-commit?

1.4k views Asked by At

I have below .pre-commit-config.yaml file.

default_language_version:
  python: python3.10
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: check-yaml
      - id: end-of-file-fixer
      - id: trailing-whitespace
      - id: check-byte-order-marker
  - repo: https://github.com/pycqa/isort
    rev: 5.12.0
    hooks:
      - id: isort
  - repo: https://github.com/psf/black
    rev: 23.7.0
    hooks:
      - id: black
  - repo: https://github.com/charliermarsh/ruff-pre-commit
    rev: 'v0.0.287'
    hooks:
      - id: ruff
        args: [--fix, --exit-non-zero-on-fix]

I have demo.py python file where few lines are exceeding max-length 88 chars, in that case pre-commit only giving E501 line too long (89 > 88 characters) error instead of re-formatting that line.

Is there any way we can auto-fix such issues?

2

There are 2 answers

0
AKX On

See the Ruff documentation:

Note that Ruff and Black treat line-length enforcement a little differently. Black makes a best-effort attempt to adhere to the line-length, but avoids automatic line-wrapping in some cases (e.g., within comments). Ruff, on the other hand, will flag rule E501 for any line that exceeds the line-length setting. As such, if E501 is enabled, Ruff can still trigger line-length violations even when Black is enabled.

IOW, no.

Since you're using Black, you can just disable the Ruff E501 rule; Black will keep your lines under its line-length (as well as it can).

Alternately, you can try the brand spanking new ruff-format hook for formatting your code and skip Black:

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.3
    hooks:
      - id: ruff
        args: [--fix, --exit-non-zero-on-fix]
      - id: ruff-format
0
EMT On

The answer is NO. And it is also logical because if a formatter break your string into two parts randomly(?!), it might cause issues in the code itself.

So, there are two things you can do.

  1. Use f-string (or multiple lines of string) and put the long line of string into multiple lines. For example, instead of the below string, 'this is very long line of text, very very long .........'

use

('this is very long line of'
'text, very very long .........'
)

Edit:

Even more pythonic way can be (for better visibility)-

(
    'this is very long line of'
    'text, very very long .........'
)
  1. You can also keep as it is in the long line and add comment to ignore the error. Just add # noqa: E501 as inline comment.