This checklist contains some tips and recommendations sorted into a syntax and a design category.
It should help to overcome common pitfalls.
-
Check your header of your file. It should contain:
a. Shebang line
#!/usr/bin/env python3
if it's a script. Leave it out if you have a module or a package.b. File docstring about the purpose of this file.
c. If needed, a list of imports; every import should occupy one line. Use
isort
to keep them sorted.d. Meta information like
__author__
,__version__
, and__url__
.e. If needed, global constants in uppercase letters.
-
Check if all your functions contain a docstring with the following properties:
a. First line with the purpose of the function.
b. Empty line.
c. One or more lines describing the arguments.
d. A line describing possible return values.
e. A line describing possible exceptions.
-
Keep your source code tidy. Why? Because, good looking source code is easier to read and maintain.
-
Follow PEP8. Use
black
or other source code formatters. -
If you write a script, add a
if ___name__ == "__main__"
line at the end. This is needed to distinguish between a module and a script. -
Be pythonic. That's a broad topic, but usually pythonic code is clear code.
-
Try to follow a naming convention for your variables:
a. Use uppercase letters for global constants.
b. Use an uppercase letter as first letter for classes.
c. Use lowercase letters for all other variables.
d. Use an underscore to indicate that a variable is "private".
-
Import only those modules or packages that you really need.
-
Restrict your imports to only the functions and classes that you really need.
-
Make sure that every of your functions fullfil only one purpose.
-
Write "simple" functions.
-
Try to limit the complexity of your code. Install the packages
python3-mccabe
andpython3-flake8
and run:$ flake8 --max-complexity 8 my_script.py
It gives you a list of functions that may be "complex", so it maybe a hint to try to make such functions simpler.
-
Use meaningful names for your function, classes, and variables:
a. Be as specific as possible.
b. Use nouns for classes and verbs for methods.
c. Use only common names for temporary variables like
i
,j
,k
,m
,n
for integers andc
,d
, ande
, for characters.