One of the best practices is, to define a common style guideline. So that it would be much easier to understand a codebase when all the code in it, is in a consistent style. Specially if you are working in a team. PEP (Python Enhancement Proposals) provides a good starting point to define those style guide.
Here are some highlights which are mostly from PEP 8, but also from other best practices:
Avoid one letter variables like x and y (Except in very short code blocks). Give your variables and functions a meaningful name and use follow naming convention:
Variables, functions, packages and modules names should be:
Classes and Exceptions
Comparisons to singletons like None should always be done with is or is not, never the equality operators.
if user is None: # Use that
if user == None # Don't use that
For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Don’t use the len() function.
if not seq: # Use that
if seq: # Use that
if len(seq): # Don't use that
if not len(seq): # Don't use that
Don’t compare boolean values to True or False using ==
if greeting: # Use that
if greeting == True: # Don't use that
Use spaces, instead of tabs (your IDE can probably convert tabs automatically to spaces). Taking 2 or 4 spaces are both fine. Just agree a convention in your team. Never mix the indentations.
Put all imports at the top of the file with three sections, each separated by a blank line, in this order:
- System imports
- Third-party imports
- Local source tree imports
That makes it clear where each module is coming from. Also Imports itself should usually be on separate lines.
Pylint is a Python static code analysis tool which looks for programming errors and help to enforce the rules of PEP 8. Most of the IDE’s have an integration of pylint. Personally I use the TensorFlow code style guide, which is based on PEP 8 and Google Python Style Guide. Just download the pylintrc file, which contains all the rules, from e.g. TensorFlow and point your pylint to that file.