28

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?

Ryu S.
  • 1,538
  • 2
  • 22
  • 41

3 Answers3

19

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.

Vincent Doba
  • 4,343
  • 3
  • 22
  • 42
Ian Stapleton Cordasco
  • 26,944
  • 4
  • 67
  • 72
16

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.

jnns
  • 5,148
  • 4
  • 47
  • 74
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
user7610
  • 25,267
  • 15
  • 124
  • 150
  • find: illegal option -- n – Omar Jan 14 '21 at 19:57
  • @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 `-`? – user7610 Jan 14 '21 at 20:07
  • 1
    @OmarS. try instead `find . -name "*.py"` – cgl May 23 '21 at 20:37
  • 1
    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) – Stephen Aug 30 '22 at 22:17