Getting Along with Python

Run syntax and style checkers

It’s good to get in a habit of frequently using automated tools to check your code for obvious syntax and style problems. Paying attention to the output of these tools can do a lot to reduce errors and improve readability. It’s really easy to be blind to issues in your own code, especially after looking at it all day.

  • A tool called pep8 scans your code to find places where you are obviously not applying PEP 8.
  • pyflakes is fast, good for integration with your editor, but not very thorough; it’s easy to satisfy as long as you don’t do anything terrible.
  • flake8 combines the functionality of pep8 and pyflakes. I’d say this is what you should use by default (and for purposes like commit hooks, if you use them.)
  • pylint is an intentionally thorough and strict tool for enforcing coding standards. You can turn off individual messages to make the feedback more relevant to you - but even so, the purpose of pylint is to complain a lot. It’s not perfect, and it doesn’t always make sense to change something only for pylint. But paying attention to what it says really can help you write cleaner code. pylint can also alert you to code which appears to be duplicated.

These are all easy to use as command-line utilities, and their usage is fully explained in their documentation as well as their --help output.

If you use these regularly, then it is less likely that you’ll let a discouraging mountain of issues pile up.

Integrating checkers with other tools

Any good editor or IDE will either allow integration with these tools, or provide some similar functionality internally.

You might also consider using a checker together with commit hooks or Continuous Integration (CI) systems. Commit hooks can require your code to pass a check before it can be committed, reducing the risk that you will accidentally commit obviously broken code for others to use. A CI server (like Jenkins or Travis CI) can monitor whether the latest versions in version control are passing checks and generate reports or notifications.

In any case where checkers are being run automatically, a major issue to consider is whether your checker will complain on incorrectly detected issues, forcing you either to turn off the automated checks (defeating the purpose of checking automatically) or to put ugly workarounds in the code to satisfy the checker (defeating the purpose of checking to improve code quality). For the purpose of commit hooks, you might want to use a low-sensitivity tool like pyflakes and reserve higher-sensitivity tools for more intensive, human-aided inspections.

See the Further Reading section below for external links that should help you get started with commit hooks and/or CI.