PyCharm Inserts Spaces on Save and then Complains

Answered

I have the Reformat Code option on among Actions on Save for *.py files. But Pycharm is inserting spaces before colons in dictionary definitions, then complaining PEP8 violation (E203). Here is a screenshot. 

and here is the error message. 

PEP 8: E203 whitespace before ':'

Any idea why this is happening and what settings should I change to avoid this conflicting behaviour? 

7 comments
Comment actions Permalink

Is it the latest PyCharm version?

Do you have any 3rd party plugins installed?

Does it insert spaces only for some dictionary items?

0
Comment actions Permalink

The version is pycharm community edition 2022.1.2 and yes, there are several plugins installed for ini, markdown, .env file support, docker etc. 

The space is inserted kinda randomly, only some dictionary items and not others. So far I am failing to see any pattern. 

 

0
Comment actions Permalink

Any chance you could share a code snippet that reproduces the problem reliably?

0
Comment actions Permalink

The same screenshot I shared in my original question. 

# Heuristic mappings obtained from https://tinyurl.com/2opmlq7h
port_service_mapping: Dict[int, str] = {20 : 'ftp', 21: 'ftp', 22: 'ssh',
25 : 'smtp', 53: 'dns', 80: 'http',
123 : 'ntp', 179: 'bgp', 443: 'https',
3389: 'rdp'}
0
Comment actions Permalink

It works fine for me with your example.
Try updating to 2022.2.2. If the issue remains, try disabling all 3rd party plugins and restarting PyCharm.

1
Comment actions Permalink

Hi Sergey, I did as you suggested, but the issue persists. From some other similar examples, it seems this is what pycharm is attempting. 

Whenever there is a dictionary being defined across multiple lines, pycharm attempts to align the first colon of every line. Hence, if the first keys of the lines have different number of characters (example above), pycharm has to pad the shorter keys with appropriate number of spaces before the colon to match the longest key. So 20, 25 above are being padded by two spaces each, 123 by one space, but no padding for 3389. 

I do not know if it goes to the root cause of the problem, but seems like a working hypothesis of what pycharm is attempting to do while inserting spaces. But is there any python standard that says the first colons should be aligned? 

0
Comment actions Permalink

Could you make sure you don't have Settings/Preferences | Editor | Code Style | Python -> Spaces -> Before ':' enabled?

2

Please sign in to leave a comment.