Tips to write pythonic

Adam Oudad
2 min readFeb 2, 2020

--

Photo by Александар Цветановић from Pexels

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-8 (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.

This is a short and straight to the point article, listing some good practices.

Naming

  • Do not use l(small L), 0(capital o) or I (capital i)for variable names, as these can be mistaken for 1 (one) and 0(zero). Seeing O = 2 gives a strange feeling…
  • 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. Python3 has significantly improved these libraries, when it comes to argument parsing, path processing, etc.

  • Handling command-line arguments with argparse
  • Logging info, error or warning messages with logging
  • To handle paths, use pathlib

Miscellaneous implementations

You can 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"')

More

PEP 8 — Style Guide for Python code

Fluent Python, by Luciano Ramalho

See this article on my website

--

--

Adam Oudad

(Machine) learning. PhD candidate, Keio University, Japan. I write about machine learning, statistics, computer science and maths.