如何禁用pycharm一段代码的格式化

Art*_*hur 5 python code-formatting pycharm

我有一些 python 代码,我想禁用它们的格式。

我知道在 java 和 intellij 中你可以通过这样做来实现这一点:

// @formatting:off

code that doesn't get formatted

// @formatting:on
Run Code Online (Sandbox Code Playgroud)

python代码和pycharm有类似的东西吗?

Lak*_*gha 7

你应该这样做。首先,在以下首选项中的注释中启用格式化程序标记;

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

然后放置格式化标记,例如;


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

#请注意行注释的用法。

顺便说一句,你的注释标记在 python 源代码中似乎不正确。我在 PyCharm 2018.3.4(社区版)上尝试过,效果很好。

进一步参考:https ://www.jetbrains.com/help/pycharm/settings-code-style.html#formatter_options

希望这可以帮助。

  • 对于 PyCharm 2021.1,位于“设置”>“编辑器”>“代码样式”>“格式化程序控制”>“在注释中启用格式化程序标记”下 (4认同)
  • 对于 PyCharm 2021.3(社区版),它显然稍微更改为“设置”>“编辑器”>“代码样式”,在此页面上选择“格式化程序”选项卡,您应该看到“在代码注释中使用标记打开/关闭格式化程序”。 (4认同)