Improving my Python coding
With leading white space governing the indentation level and so the grouping of statements, Python code already looks relatively clean.
Yet there are additional tools that will help you improve your code.
Pyflakes
The pyflakes checker tries very hard to find errors in Python source files. (It does not care about style.)
Pycodestyle
So for style I use pycodestyle checker (formerly known as pep8
).
It checks your code against the conventions of PEP 8.
Personally I do like to relax the PEP 8 maximum line length of 79 characters.
In general I like to try to keep line length below 80 characters. But if
incidentally is somewhat more, It doesn’t bother me. So I generally use
pycodestyle
with the argument --max-line-length=100
.
Syntastic
This is a plugin for the vim editor that lets you run checker programs on
your code when you save it. Currently I use this to run
python
, pycodestyle and pyflakes.
Since I save regularly, I get fast feedback on errors and potential issues. This has probably been the most helpful in teaching me good coding habits and solving problems when they occur.
Pydocstyle
Documentation is almost as important as your code; it is probably the first thing that a user of a module will read.
So I’m in the process of checking all my Python code with pydocstyle.
Since some of the default checks that it runs are contradictory, I’ve created
a .pydocstylerc
file in my home directory with the following contents:
[pydocstyle]
ignore = D203,D212,D406,D407,D408,D409,D413
This ignores the following violations that I don’t agree with:
- D203
- 1 blank line required before class docstring. (Contradicts D211).
- D212
- Multi-line docstring summary should start at the first line. (Contradicts D213).
- D406
- Section name should end with a newline. (Complains about “Returns:” instead of “Returns”).
- D407,D408,D409
- All about underlining section names, which I don’t do.
- D413
- Missing blank line after last section.
Yapf
While yapf is a excellent reformatting tool, it has some limitations on
Python 3. It crashes hard on unicode identifiers, because of its internal
usage of lib2to3
.
It works fine when your code does not contain unicode identifiers, though. I use it with its standard settings.
For comments, please send me an e-mail.
Related articles
- Profiling Python scripts(6): auto-orient
- Profiling with pyinstrument
- From python script to executable with cython
- On Python speed
- Python 3.11 speed comparison with 3.9