Much of the material in this document is taken from Appendix F in the book A Primer on Scientific Programming with Python, 4th edition, by the same author, published by Springer, 2014.
The tools PyLint and Flake8 can analyze your code and point out errors and undesired coding styles. Before point 7 in the lists above, Run the program, it can be wise to run PyLint or Flake8 to be informed about problems with the code.
Consider the first version of the integrate
code,
integrate_v1.py. Running Flake8 gives
Terminal> flake8 integrate_v1.py
integrate_v1.py:7:1: E302 expected 2 blank lines, found 1
integrate_v1.py:8:1: E112 expected an indented block
integrate_v1.py:8:7: E901 IndentationError: expected an indented block
integrate_v1.py:10:1: E302 expected 2 blank lines, found 1
integrate_v1.py:11:1: E112 expected an indented block
Flake8 checks if the program obeys the official
Style Guide for Python Code
(known as PEP8). One of the rules in this guide is to have two
blank lines before functions and classes (a habit that is often dropped
in this document to reduce the length of code snippets), and our
program breaks the rule before the f
and g
functions.
More serious and useful is the expected an indented block
at lines 8 and 11.
This error is quickly found anyway by running the programming.
PyLint does not a complete job before the program is free of syntax errors. We must therefore apply it to the integrate_v2.py code:
Terminal> pylint integrate_v2.py
C: 20, 0: Exactly one space required after comma
I = integrate(f, 0, 1, n)
^ (bad-whitespace)
W: 19, 0: Redefining built-in 'pow' (redefined-builtin)
C: 1, 0: Missing module docstring (missing-docstring)
W: 1,14: Redefining name 'f' from outer scope (line 8)
W: 1,23: Redefining name 'n' from outer scope (line 16)
C: 1, 0: Invalid argument name "f" (invalid-name)
C: 1, 0: Invalid argument name "a" (invalid-name)
There is much more output, but let us summarize what PyLint does not like about the code:
integrate
)f
used as local variable in integrate
and
global function name in the f(x)
functiona
, b
, n
, etc.from math import *
Running Flak8 on integrate_v2.py
leads to only three problems:
missing two blank lines before functions (not reported by PyLint)
and doing from math import *
. Flake8 complains in general
a lot less than PyLint, but both are very useful during
program development to readability of the code and remove errors.