Python is a versatile language loved for its simplicity and powerful libraries. However, as a developer tackling real-world software problems, having a set of go-to snippets can save you hours of debugging and coding. Whether you’re integrating APIs, handling files, or managing large datasets, these 10 Python snippets are designed to help you solve common challenges with ease.
1. Reading a JSON Config File
When building enterprise software, configurations are often stored in JSON files. Here’s a quick way to load them:
pythonCopyEditimport json
def load_config(file_path):
try:
with open(file_path, 'r') as file:
config = json.load(file)
return config
except FileNotFoundError:
print(f"Error: {file_path} not found.")
except json.JSONDecodeError:
print("Error: Invalid JSON format.")
Usage:
pythonCopyEditconfig = load_config("config.json")
print(config.get("database_url", "Default_URL"))
2. Sending an HTTP Request with Retry Logic
Interacting with APIs? Use this snippet for resilient HTTP requests with retries.
pythonCopyEditimport requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def get_with_retries(url, retries=3):
session = requests.Session()
retry_strategy = Retry(
total=retries,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504]
)
session.mount("http://", HTTPAdapter(max_retries=retry_strategy))
session.mount("https://", HTTPAdapter(max_retries=retry_strategy))
response = session.get(url)
response.raise_for_status()
return response.json()
Usage:
pythonCopyEditdata = get_with_retries("https://api.example.com/data")
print(data)
3. Efficient File Processing with Generators
Working with large log files? Process them line by line to save memory.
pythonCopyEditdef process_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
# Usage example
for line in process_large_file("large_log.txt"):
if "ERROR" in line:
print(line)
4. Connecting to a Database (SQLAlchemy)
Database operations are essential in enterprise applications. This snippet connects to a PostgreSQL database using SQLAlchemy.
pythonCopyEditfrom sqlalchemy import create_engine
def connect_to_db(user, password, host, dbname):
engine = create_engine(f"postgresql://{user}:{password}@{host}/{dbname}")
return engine.connect()
# Usage example
connection = connect_to_db("user", "password", "localhost", "my_database")
print("Connected to database!")
5. Measure Code Execution Time
Optimize your code by measuring its performance.
pythonCopyEditimport time
def time_it(func, *args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution time: {end - start:.4f} seconds")
return result
# Usage example
def slow_function():
time.sleep(2)
time_it(slow_function)
6. Handling Multi-Threading with ThreadPoolExecutor
Boost performance for I/O-bound tasks using threads.
pythonCopyEditfrom concurrent.futures import ThreadPoolExecutor
def task(name):
print(f"Task {name} is starting.")
time.sleep(1)
print(f"Task {name} is complete.")
with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(10):
executor.submit(task, i)
7. Dynamic Function Decorator for Logging
Simplify debugging with a decorator that logs function calls.
pythonCopyEditdef log_calls(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args} kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_calls
def add(a, b):
return a + b
add(3, 4)
8. Simple Caching with functools.lru_cache
Avoid redundant calculations using built-in caching.
pythonCopyEditfrom functools import lru_cache
@lru_cache(maxsize=100)
def expensive_computation(x):
print(f"Computing {x}...")
return x * x
print(expensive_computation(10))
print(expensive_computation(10)) # Cached result
9. Parsing and Validating Dates with dateutil
Work with dates confidently using the python-dateutil
library.
pythonCopyEditfrom dateutil.parser import parse
from datetime import datetime
def validate_date(date_str):
try:
date = parse(date_str)
print(f"Valid date: {date}")
return date
except ValueError:
print("Invalid date format.")
# Usage example
validate_date("2025-01-19")
10. Creating a Custom Exception
Handle domain-specific errors with custom exceptions.
pythonCopyEditclass InvalidConfigError(Exception):
pass
def load_config(file_path):
if not file_path.endswith('.json'):
raise InvalidConfigError("Config file must be a JSON file.")
# Load the config (as shown earlier)
# Usage
try:
load_config("config.txt")
except InvalidConfigError as e:
print(f"Error: {e}")
Conclusion
These Python snippets are more than just tricks—they’re tools to make you a faster, more efficient developer. Whether you’re optimizing code performance, integrating APIs, or managing enterprise-level software challenges, keeping these snippets at hand will save you time and effort. Which snippet will you add to your toolbox today?