Improve Your Python Code Automatically
Improve Your Python Code Automatically
Code Review
GitHub View on GitHub Book View Book
This section covers some tools to automatically review and improve your
code such as sorting imports, check for missing docstrings, etc.
isort: Automatically Sort your Python Imports in 1
Line of Code
As your codebase expands, you may find yourself importing numerous
libraries, which can become overwhelming to navigate. To avoid arranging
your imports manually, use isort.
You can use isort with pre-commit by adding the following to your .pre-
commit-config.yaml file:
- repo: https://github.com/timothycrosley/isort
rev: 5.12.0
hooks:
- id: isort
Link to isort.
interrogate: Check your Python Code for Missing
Docstrings
!pip install interrogate
Sometimes, you might forget to include docstrings for classes and functions.
Instead of manually searching through all your functions and classes for
missing docstrings, use interrogate.
# interrogate_example.py
class Math:
def __init__(self, num) -> None:
self.num = num
def plus_two(self):
"""Add 2"""
return self.num + 2
def multiply_three(self):
return self.num * 3
You can use interrogate to identify missing docstrings:
$ interrogate interrogate_example.py
Output:
You can use interrogate with pre-commit by adding the following to your
.pre-commit-config.yaml file:
- repo: https://github.com/pre-commit/mirrors-interrogate
rev: v1.4.0
hooks:
- id: interrogate
Link to interrogate.
mypy: Static Type Checker for Python
# mypyÏ_example.py
from typing import List, Union
$ mypy mypy_example.py
You can use mypy with pre-commit by adding the following to your .pre-
commit-config.yaml file:
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910
hooks:
- id: mypy
Link to mypy.
Refurb: Refurbish and Modernize Python Codebases
If you want to have some guidelines to improve and optimize your code, try
Refurb.
# test_refurb.py
for n in [1, 2, 3, 4]:
if n == 2 or n == 4:
res = n/2
$ refurb test_refurb.py
['Since tuple, list, and set literals can be used with the
`in` operator, it',
'is best to pick one and stick with it.',
'',
'Bad:',
'',
'```',
'for x in [1, 2, 3]:',
' pass',
'',
'nums = [str(x) for x in [1, 2, 3]]',
'```',
'',
'Good:',
'',
'```',
'for x in (1, 2, 3):',
' pass',
'',
'nums = [str(x) for x in (1, 2, 3)]',
'```']
repos:
- repo: https://github.com/dosisod/refurb
rev: REVISION
hooks:
- id: refurb
Link to Refurb.
Pydantic: Enforce Data Types on Your Function
Parameters at Runtime
!pip install pydantic
If you want to enforce data types on your function parameters and validate
their values at runtime, use Pydantic.
In the code below, since the value of test_size is a string, Pydantic raises a
ValidationError.
class ProcessConfig(BaseModel):
drop_columns: list = ["a", "b"]
target: str = "y"
test_size: float = 0.3
random_state: int = 1
shuffle: bool = True
def process(config: ProcessConfig = ProcessConfig()):
target = config.target
test_size = config.test_size
...
process(ProcessConfig(test_size="a"))
Link to Pydantic.
If you want to compare the performance between different snippets and plot
the results, use perfplot.
Consider the following file that includes three functions that create a list.
import perfplot
def append(n):
l = []
for i in range(n):
l.append(i)
return l
def comprehension(n):
return [i for i in range(n)]
def list_range(n):
return list(range(n))
To visualize the perfomance of these functions, use the perfplot.show
method.
perfplot.show(
setup=lambda n: n,
kernels=[
append,
comprehension,
list_range,
],
n_range=[2**k for k in range(25)],
)
Link to perfplot.
Analyze the Memory Usage of Your Python Code
!pip install memory_profiler
If you want to analyze the memory consumption of your Python code line-
by-line, use memory_profiler. This package allows you to generate a full
memory usage report of your executable and plot it.
$ mprof plot
Link to memory_profiler.