Black: Incorrectly adds space in slice

Created on 4 Dec 2020  ·  2Comments  ·  Source: psf/black

Describe the bug
Black adds a space before the colon in a string slice with no upper bound
To Reproduce

a = "foo"
b = a[len(a) - 2:]

when run on black with no arguments produces

a = "foo"
b = a[len(a) - 2 :]

Expected behavior A clear and concise description of what you expected to happen.
The correct behavior would be to output

a = "foo"
b = a[len(a) - 2:]

Environment (please complete the following information):

  • Version: 20.8b1
  • OS and Python version: Linux/Python 3.8.1

Does this bug also happen on master? To answer this, you have two options:
Yes

Additional context Add any other context about the problem here.
flake8 and PyCharm both report "E203 whitespace before ':'" with Black's current output

The correct behavior is inferred from this example from the pep8 document ham[1:9:]

I'm currently working around this with # fmt: off since our files have to pass flake8.

duplicate not a bug

All 2 comments

There is no end to this torment of E203 bug reports ... :D

A duplicate of #1841, #1701, #1563, #1541, #1448, #1437, #1413, #1343, #1332, #1323, #1029, #889, #785, #565, #544, #492, #403, #354, #350, #311, #279, #264, and #227...

Since I honestly don't care about these issues anymore, imma copy and paste what's in our docs (emphasis mine):

PEP 8 recommends to treat : in slices as a binary operator with the lowest priority, and to leave an equal amount of space on either side, except if a parameter is omitted (e.g. ham[1 + 1 :]). It recommends no spaces around : operators for “simple expressions” (ham[lower:upper]), and extra space for “complex expressions” (ham[lower : upper + offset]). Black treats anything more than variable names as “complex” (ham[lower : upper + 1]). It also states that for extended slices, both : operators have to have the same amount of spacing, except if a parameter is omitted (ham[1 + 1 ::]). Black enforces these rules consistently.

This behaviour may raise E203 whitespace before ':' warnings in style guide enforcement tools like Flake8. Since E203 is not PEP 8 compliant, you should tell Flake8 to ignore these warnings.

https://black.readthedocs.io/en/stable/the_black_code_style.html#slices

Have a good day! At this point it's just plain funny (minus the notification)!

Sorry, I didn't search for E203. :(

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dgnsrekt picture dgnsrekt  ·  3Comments

JelleZijlstra picture JelleZijlstra  ·  3Comments

craigmac picture craigmac  ·  3Comments

Curly-Mo picture Curly-Mo  ·  3Comments

decibyte picture decibyte  ·  3Comments