50

I am trying to disable vscode from formatting my python imports when I save my file. I have some code that must run in between various imports so order is important, but every time I save it just shoves the imports to the top.

I tried putting

"editor.codeActionsOnSave": {
    "source.organizeImports": false
},

in my user settings but that doesn't fix it.

Thanks!

EDIT- I would like to keep formatting on save on except for the imports

Lukas Schmit
  • 1,118
  • 2
  • 9
  • 14
  • 1
    Does this answer your question? [Formatting on save moves import statment in VS-Code](https://stackoverflow.com/questions/53579109/formatting-on-save-moves-import-statment-in-vs-code) – Cees Timmerman Dec 14 '20 at 03:57

1 Answers1

78

Check for the below setting in vscode settings, if it's true then set it to false for completely disabling formatting on save, like so :

 "editor.formatOnSave": false

for formatting and to ignore imports not being at top itself, first make the above setting true and add to your user settings and try adding this setting to your user settings, if you're using the default formatter for python, that is autopep8 :

"python.formatting.autopep8Args": ["--ignore","E402"]  

where E402 represents "module level import not at top of file"

Note that this would only work if you are using the default formatter/linter. If you are using some other linter then i suggest you look up their documentation to see how it's done. Like most commonly one could make use of global config file, say $HOME/.config/.pycodestyle, and add necessary settings there, like :

[pycodestyle]
ignore = E402  

EDIT : the arguments for the formatter should be passed as separate list items in quotes like ["--ignore","E402"] rather than [--ignore=E402]

Yedhin
  • 2,931
  • 13
  • 19
  • That looks promising! I am using the default formatter, but "python.formatting.autopep8Args": [--ignore=E402] gives an error. It says Value Expected jsonc 516. Any ideas? – Lukas Schmit Jan 03 '19 at 09:05
  • 5
    not sure but can you try this : ```"python.formatting.autopep8Args": ["--ignore","E402"]```. Like put the args as seperate list items inside quotes – Yedhin Jan 03 '19 at 09:38
  • 1
    Relevant VS Code docs on Python-specific formatter settings: https://code.visualstudio.com/docs/python/editing#_formatting – Gino Mempin Feb 27 '21 at 05:45
  • strangely, but as soon as I add this argument ["--ignore","E402"], the formatting is entirely disabled, and the code is not formatted any longer... – Dark Templar Apr 27 '21 at 12:08
  • @DarkTemplar I'd probably check the project specific or global config for the particular formatter that you are using, which might be disabling certain format features. – Yedhin Apr 28 '21 at 13:05