Show Menu
Cheatography

Python Debugging Cheat Sheet (DRAFT) by [deleted]

Useful tools/methods for debugging python code

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Module: time

import time
(python3 doc)
time.t­ime()
: returns the time in seconds since the epoch as a floating point number
The epoch is OS-dep­endent, and is given by
time.g­mti­me(0)

Module: timeit

TODO

Method­ology : Decorator and print()

def timing_func(f):
    def wrapper(*args, **kwargs):
        tic = time.time()
        res = f(*args, **kwargs)
        toc = time.time()
        print('{0} running time: {1} secs'.format(f.__name__, toc-tic))
        return res
Use: Decorator @timin­g_func on functions to be timed, which is syntactic sugar for some_func = timing­_fu­nc(­som­e_func)
Note: To preserve attributes of some_func, use @wraps decorator from the functools module on wrapper

Method­ology: *nix time command

$ /usr/bin/time -p python my_module.py
real 12.37
user 12.15
sys 0.09
Note: use system /usr/b­in/time (man page) rather than shell time, as the former comes with a --verbose option
real: wall clock or elapsed time
user: amount of time the CPU spent on your task outside of kernel functions
sys: time spent in kernel functions
Useful for: segreg­ating time my_mod­ule.py spends in CPU, from time spent on other kernel­-level tasks, or other background processes
 

Module: line_p­rofiler

 
Porting from Python2 to Python3: explained in this stacko­verflow thread

Module: cProfile