Tips to write pythonic
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) orI
(capital i)for variable names, as these can be mistaken for1
(one) and0
(zero). SeeingO = 2
gives a strange feeling… - Choose explicit names.
learning_rate
is 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):
passdef my_other_method(self):
passclass 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