Adam Oudad

Adam Oudad

(Machine) Learning log.

2 minutes read

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, 0 or I for variable names, as these can be mistaken for 1 and 0. O = 2 is weird
  • Choose explicit names. learning_rate is better than lr
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:
    pass

Line 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 startwith and endwith methods for str objects

    # Not recommended :(
    if word[:3] == 'cat':
        print('The word starts with "cat"')
    
    # Recommended :)
    if word.startswith('cat'):
        print('The word starts with "cat"')
  • Use pathlib

    from pathlib import Path
    data_path = Path("/home/adam/")
    midi_path = data_path / "midi"
    # Be careful of errors, sometimes use str(midi_)

Footnotes


1

PEP 8 – Style Guide for Python code https://www.python.org/dev/peps/pep-0008/

comments powered by Disqus

Recent posts

See more

Categories

About

This website is a weblog were I write about computer science, machine learning, language learning.