Debugging Tips & Cool Features & More Handy Tricks
1. Use pdb for Debugging
import pdb; pdb.set_trace()
2. Print Formatted JSON
import json
print(json.dumps(my_dict, indent=4))
3.Use assert Statements for Quick Testing
assert my_func() == expected_value
4. Use try-except to Handle Exceptions Gracefully
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
5. Log Messages with logging Module
import logging
logging.basicConfig(level=logging.DEBUG)
Cool Features
- Use
dataclassesfor Class Boilerplate Reduction (Python 3.7+)
from dataclasses import dataclass
@dataclass
class Car:
make: str
model: str
2. Convert Lists into a Dictionary
keys = ['a', 'b']
values = [1, 2]
my_dict = dict(zip(keys, values))
3. Use partial for Pre-Setting Function Arguments
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, 2)
4. Generate Random Choices with random.choice
import random
choice = random.choice(my_list)
5.Find the Most Frequent Element with max and count
most_frequent = max(set(my_list), key=my_list.count)
More Handy Tricks
1.Filter Elements with filter()
evens = list(filter(lambda x: x % 2 == 0, my_list))
2. Map and Apply Functions to Elements
squared = list(map(lambda x: x**2, my_list))
3. Flatten Nested Lists with sum()
flattened = sum(nested_list, [])
4. Download Files Using requests
import requests
r = requests.get('https://example.com')
5. Use any() and all() for Logical Checks
if any([a > 5 for a in my_list]):
print("There’s a value greater than 5.")