Advanced Troubleshooting
Memory Profiling and Optimization
Memory Usage Analysis
import memory_profiler
@memory_profiler.profile
def memory_intensive_function():
large_list = [x for x in range(1000000)]
return sum(large_list)
memory_intensive_function()
Complex Error Tracking
Custom Exception Handling
class AdvancedError(Exception):
def __init__(self, message, error_code):
self.message = message
self.error_code = error_code
super().__init__(self.message)
def advanced_error_handling():
try:
## Complex logic
if some_condition:
raise AdvancedError("Specific error occurred", 500)
except AdvancedError as e:
print(f"Error Code: {e.error_code}")
print(f"Error Message: {e.message}")
Debugging Workflow
graph TD
A[Identify Issue] --> B{Reproduce Problem}
B --> |Yes| C[Isolate Code Section]
B --> |No| D[Gather More Information]
C --> E[Analyze Potential Causes]
E --> F[Implement Temporary Fix]
F --> G[Develop Permanent Solution]
Timing Decorator
import time
import functools
def timing_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
return result
return wrapper
@timing_decorator
def complex_computation(n):
return sum(i**2 for i in range(n))
Tool |
Purpose |
Key Features |
pyinstrument |
Performance Profiling |
Low overhead |
py-spy |
Sampling Profiler |
No code modification |
hypothesis |
Property-based Testing |
Automated test generation |
Concurrent Debugging
Multiprocessing Debugging
import multiprocessing
import traceback
def worker_function(x):
try:
## Complex concurrent operation
result = x * x
return result
except Exception as e:
print(f"Error in worker: {e}")
traceback.print_exc()
def run_multiprocessing():
with multiprocessing.Pool(processes=4) as pool:
try:
results = pool.map(worker_function, range(10))
print(results)
except Exception as e:
print(f"Multiprocessing error: {e}")
Advanced Logging Configuration
import logging
import sys
def configure_advanced_logging():
## Create logger
logger = logging.getLogger('advanced_logger')
logger.setLevel(logging.DEBUG)
## Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
## File handler
file_handler = logging.FileHandler('debug.log')
file_handler.setLevel(logging.DEBUG)
## Formatters
console_formatter = logging.Formatter('%(message)s')
file_formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
console_handler.setFormatter(console_formatter)
file_handler.setFormatter(file_formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
System-Level Debugging
Tracing System Calls
import sys
import trace
def trace_calls():
tracer = trace.Trace(
count=1, ## Count of calls
trace=1, ## Trace execution
countfuncs=1 ## Count function calls
)
tracer.run('your_main_function()')
Note: LabEx recommends continuous learning and practice to master advanced troubleshooting techniques in Python.