How to disable pycharm formatting for a section of code
Asked Answered
R

1

8

I've got some python code for which I'd like to disable formatting.

I know in java and with intellij you can achieve this by doing:

// @formatting:off

code that doesn't get formatted

// @formatting:on

Is there something similar for python code and pycharm?

Rempe answered 18/2, 2019 at 14:41 Comment(0)
A
8

This is how you should do it. First, enable formatter markers in comments in Preferences following;

Preferences -> Code Style -> Formatter Control -> Tick Enable formatter markers in comments

Then place your formatter markers as, for example;


# @formatter:off
df = pd.DataFrame({'height':    height, 'weight':   weight}, columns=['height', 'weight'])
df.plot.scatter(x='height', y='weight')
#@formatter:on

Note the usage of # for line comments.

Your comment markers seem to be incorrect in python source code by the way. I tried this on PyCharm 2018.3.4 (Community Edition) and works fine.

Further reference: https://www.jetbrains.com/help/pycharm/settings-code-style.html#formatter_options

Hope this helps.

Andalusite answered 18/2, 2019 at 14:55 Comment(5)
Does it also fork for import order?Rempe
For PyCharm 2021.1 that's under Settings > Editor > Code Style > Formatter Control > Enable formatter markers in commentsNashville
@Nashville And seems to have disappeared again in PyCharm 2021.2.3Whistle
For PyCharm 2021.3 (Community Edition) it was apparently slightly changed to Settings > Editor > Code Style, on this page select the tab "Formatter", there you should see "Turn formatter on/off with markers in code comments".Nashville
The problem with this solution is that it follows the same standards as other formatters so this will effectively disable all code formatters.Gatlin

© 2022 - 2024 — McMap. All rights reserved.