How do I enable auto code formatting for flake8 in PyCharm
Asked Answered
L

3

32

I use Tox to run unit tests, with a flake8 command that checks for code formatting errors. Each time I code in PyCharm, I run tox then realise I have a bunch of annoying formatting errors I have to back and manually fix. I would like PyCharm to automatically format the code (according to flake8 google for me each time it auto-saves after I stop typing.

my tox testenv looks like this:

[testenv:flake8]
commands=flake8 <my_code_directory>
deps =     
  flake8==2.4.1    
  flake8-import-order==0.11    
  pep8-naming==0.4.1 

[flake8] 
max-line-length = 120 
import-order-style = google

Is this possible? Do I have to download a specific plugin somewhere? If not with flake8, what about just PEP-8?

Lemire answered 27/1, 2017 at 16:49 Comment(0)
L
20

Flake8 and import ordering are not auto-fixable in a way that complies with what you're seeing. You can auto-fix pep8 with autopep8.

There are discussions here about implementing this for Flake8 though.

Lais answered 28/1, 2017 at 17:14 Comment(0)
N
17

For automatically sorting import statements use isort. Consider using black to auto-format your Python code.

Edit: ruff can replace flake8 and isort and is also much faster because it's based on Rust. It also supports LSP, so PyCharm you should be able to use it from within PyCharm.

Normanormal answered 27/11, 2018 at 15:8 Comment(0)
L
12

The tool you want is probably autopep8. This is especially because the warning codes it uses correspond to the flake8 ones.

For example, if you want to autofix all instances of E701 multiple statements on a single line warning, run the following

for f in `find . -name "*.py"`; do autopep8 --in-place --select=E701 $f; done
Lichenology answered 26/10, 2020 at 19:36 Comment(4)
find: illegal option -- nGudrin
@OmarS. Interesting. Your find is probably different from my find :P. I use it there to print all .py files in current directory and sub-directories. If you find out how to do that on your machine, let me know. Maybe, try -- instead of -?Lichenology
@OmarS. try instead find . -name "*.py"Rhu
I can't get autopep to actually modify the file. I am trying to address F401: autopep8 --in-place --select=F401 --aggressive path/to/my/file.py. My versions are: autopep8 1.7.0 (pycodestyle: 2.9.1)Sheridansherie

© 2022 - 2024 — McMap. All rights reserved.