Python community has a special words for talking about code that follows the best practices for writing in python, pythonic. The following are some tips to make the most of Python programming language.
I recommend as reference the PEP-81 (Python Enhancement Proposal) document which provides guidelines and best practices on how to write Python code. It enables to achieve better readability and consistency throughout code.
Naming
- Never use l,0orIfor variable names, as these can be mistaken for1and0.O = 2is weird
- Choose explicit names. learning_rateis better thanlr
| Topic | Good examples | Bad examples | 
|---|---|---|
| Function | function, my_function | MyFunction, func | 
| Variable | x, var, my_variable | Var, Myvar | 
| Class | Model, MyClass | model, my_class | 
| Method | class_method, method | |
| Constant | CONSTANT, MY_CONSTANT | myconstant | 
| Module | module.py, my_module.py | my-module.py | 
| Package | package, mypackage | 
Blank lines
- Blank lines help readability
class MIDIScore:
    def my_method(self):
        pass
 
    def my_other_method(self):
        pass
class Pianoroll:
    passLine breaking
- Use maximum line length of 79
- 
Break lines if necessary, with ( ),\total = (first_variable + second_variable - third_variable) from mypkg import example1, \ example2, example3
Indentation
- 
Use it to improve readability def train(model, weights, data, epochs, batch_size): model.load_weights(weights) model.fit(data, epochs, batch_size)
Use built-in libraries
Instead of reinventing the wheel, most common processing can be done using built-in features of python default libraries.
- Handling command-line arguments
- argparse
- Logging info, error or warning messages
- logging
- Using paths
- 
pathlib from pathlib import Path # Define Path object data_path = Path("/data/") # Composing paths mozart_k330_path = data_path / "midi" / "mozart_k330.mid" # Iterating over list of .mid files, following subdirectories for p in (data_path / "midi").glob("**/*.mid"): print(p) # Open file with mozart_k330_path.open('r') as f: pass
Implementations
- 
Use startwithandendwithmethods forstrobjects# Not recommended :( if word[:3] == 'cat': print('The word starts with "cat"') # Recommended :) if word.startswith('cat'): print('The word starts with "cat"')
- 
Use pathlibfrom pathlib import Path data_path = Path("/home/adam/") midi_path = data_path / "midi" # Be careful of errors, sometimes use str(midi_)
Footnotes
PEP 8 – Style Guide for Python code https://www.python.org/dev/peps/pep-0008/
