Tue, 13 Oct 2009

Good Python Habits: vim + pyflakes

Here is a neat little hack for running pyflakes on Python files after you save them. I like using pyflakes for quickly catching dumb errors, but you could easily replace it with a more comprehensive tool like pychecker, or pylint for more strict PEP8 compliance.

All you have to do is throw this in your ~/.vimrc

au BufWritePost *.py !pyflakes %

This has saved me *tons* of time and frustration over the past few weeks, and I have no idea I lived without it.


posted at: 13:32 | link | Tags: , , | 3 comments

Posted by Chicha at Tue Oct 13 14:09:40 2009

Hi,

Thank you very much for introducing pyflakes, I did not know about it !

Did you tried Pylint (http://www.logilab.org/857) ?
If so what is your opinion about pylint vs pyflakes ?

Thanks a lot for your feedback !
Cheers,
Chicha

Posted by Luke at Tue Oct 13 17:14:28 2009

Chicha,

I do use pylint on a fairly regular basis, but I find it way too slow and verbose by default to integrate into vim in this way (I'm sure you can probably pass it various arguments to change that though).  Pyflakes, even though it doesn't detect as many problems as pylint, is very very fast.

Posted by Toshio at Fri Oct 16 06:04:16 2009

@Luke, Cool!  I had this in my .vimrc to catch SyntaxErrors::
  au BufWritePost *.py !python -c 'import py_compile; py_compile.compile("%")'

but pyflakes is an even better idea!


@Chicha, For doing a periodic cleanup of your source code nothing else I've seen beats pylint.  It's very comprehensive; catches style problems, errors, potential logic problems, etc; can be customized to only show you certain warnings; and has the ability to tell you whether your code's score is going up or down... provoking you to try to constantly improve your code.

Compared to pylint, pyflakes still lets you make some pretty rudimentary mistakes.  For instance:

test.py::
  import TurboGears
  improt cherrypy

pylint and pyflakes will both catch the typoed "improt" in the second line.  However, only pylint will catch that there is no Turbogears module (the module name is turbogears... all lowercase).

But pylint has two noticable drawbacks in this particular application:

1) pylint is more adapted to working on whole projects than to individual files.  pylint analyzes the modules that your file imports.  If you import other python files from your project using absolute imports, pylint may not be able to find them if you're not in the expected directory.

2) pylint is slower than pyflakes.  Probably because pylint is so comprehensive, it takes quite a while to analyze your code.

I wouldn't do without running pylint over my python projects periodically.  However, pyflakes is probably more appropriate as something run whenever you save a python file.


Name:


E-mail:


URL:


Comment: