Tools for Logging and Debugging in Python 1639039318
Tools for Logging and Debugging in Python 1639039318
If you want to quickly see which attributes and methods of a Python object are available,
use rich’s inspect method.
rich’s inspect method allows you to create a beautiful report for any Python object,
including a string.
print(inspect('hello', methods=True))
Sometimes, you might want to know which elements in the function created a certain
output. Instead of printing every variable in the function, you can simply use Rich’s
Console object to print both the output and all the variables in the function.
console = Console()
def edit_data(data):
var_1 = 45
var_2 = 30
var_3 = var_1 + var_2
data['a'] = [var_1, var_2, var_3]
console.log(data, log_locals=True)
edit_data(data)
[08:12:24] a b
0 45 4
1 30 5
2 75 6
╭───── locals ─────╮
│ data = a b │
│ 0 45 4 │
│ 1 30 5 │
│ 2 75 6 │
│ var_1 = 45 │
│ var_2 = 30 │
│ var_3 = 75 │
╰──────────────────╯
Link to my article about rich.
Link to rich.
loguru: Print Readable Traceback in Python
Sometimes, it is difficult to understand the traceback and to know which inputs cause the
error. Is there a way that you can print a more readable traceback?
@logger.catch
def evaluate_result(y_true: np.array, y_pred: np.array):
mean_square_err = mean_squared_error(y_true, y_pred)
root_mean_square_err = mean_square_err ** 0.5
File "/home/khuyen/book/venv/lib/python3.8/site-
packages/sklearn/utils/validation.py", line 63, in inner_f
return f(*args, **kwargs)
│ │ └ {}
│ └ (array([1, 2, 3]), array([1.5, 2.2]))
└ <function mean_squared_error at 0x7f27958bfb80>
File "/home/khuyen/book/venv/lib/python3.8/site-
packages/sklearn/metrics/_regression.py", line 335, in
mean_squared_error
y_type, y_true, y_pred, multioutput = _check_reg_targets(
│ │ └ <function
_check_reg_targets at 0x7f27958b7af0>
│ └ array([1.5, 2.2])
└ array([1, 2, 3])
File "/home/khuyen/book/venv/lib/python3.8/site-
packages/sklearn/metrics/_regression.py", line 88, in
_check_reg_targets
check_consistent_length(y_true, y_pred)
│ │ └ array([1.5, 2.2])
│ └ array([1, 2, 3])
└ <function check_consistent_length at 0x7f279676e040>
File "/home/khuyen/book/venv/lib/python3.8/site-
packages/sklearn/utils/validation.py", line 319, in
check_consistent_length
raise ValueError("Found input variables with inconsistent
numbers of"
Link to loguru.
Icrecream: Never use print() to debug again
!pip install icecream
If you use print or log to debug your code, you might be confused about which line of
code creates the output, especially when there are many outputs.
def plus_one(num):
return num + 1
Try icecream instead. Icrecream inspects itself and prints both its own arguments and the
values of those arguments like below.
ic(plus_one(1))
ic(plus_one(2))
ic| plus_one(1): 2
ic| plus_one(2): 3
Output:
ic| plus_one(1): 2
ic| plus_one(2): 3
Link to icecream
If you want to visualize which lines are executed and how many times they are executed,
try heartrate.
import heartrate
heartrate.trace(browser=True)
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
if __name__ == "__main__":
num = 5
print(f"The factorial of {num} is {factorial(num)}")
You should see something similar to the below when opening the browser:
Link to heartrate.