Practical Usage Patterns
Common Utility Function Categories
graph TD
A[Utility Function Types] --> B[Data Manipulation]
A --> C[Validation]
A --> D[Transformation]
A --> E[System Interaction]
Data Manipulation Utilities
def filter_positive_numbers(numbers: list) -> list:
"""
Filter out positive numbers from a list.
Args:
numbers: Input list of numbers
Returns:
List of positive numbers
"""
return [num for num in numbers if num > 0]
## Example usage
data = [-1, 2, -3, 4, 0, 5]
positive_nums = filter_positive_numbers(data)
print(positive_nums) ## Output: [2, 4, 5]
Data Cleaning Utilities
def clean_string_data(text: str) -> str:
"""
Clean and normalize string data.
Args:
text: Input string
Returns:
Cleaned and normalized string
"""
return text.strip().lower()
## Example usage
raw_input = " Python Programming "
cleaned_input = clean_string_data(raw_input)
print(cleaned_input) ## Output: "python programming"
Validation Utilities
Validation Type |
Description |
Example |
Type Checking |
Verify input types |
isinstance(value, int) |
Range Validation |
Check value ranges |
0 <= value <= 100 |
Format Validation |
Validate string formats |
re.match(pattern, string) |
def validate_email(email: str) -> bool:
"""
Validate email address format.
Args:
email: Email address to validate
Returns:
Boolean indicating valid email format
"""
import re
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None
## Example usage
print(validate_email('[email protected]')) ## True
print(validate_email('invalid_email')) ## False
Data Type Conversion
def safe_convert(value: str, convert_type: type, default=None):
"""
Safely convert values between types.
Args:
value: Value to convert
convert_type: Target type
default: Fallback value if conversion fails
Returns:
Converted value or default
"""
try:
return convert_type(value)
except (ValueError, TypeError):
return default
## Example usage
print(safe_convert('42', int)) ## 42
print(safe_convert('3.14', float)) ## 3.14
print(safe_convert('abc', int, 0)) ## 0
System Interaction Utilities
File and Path Handling
import os
def ensure_directory(path: str) -> bool:
"""
Ensure a directory exists, creating if necessary.
Args:
path: Directory path
Returns:
Boolean indicating directory existence
"""
try:
os.makedirs(path, exist_ok=True)
return True
except OSError:
return False
## Example usage
result = ensure_directory('/tmp/my_project')
print(result) ## True if directory created or exists
Advanced Composition Techniques
Functional Composition
def compose(*functions):
"""
Create a function composition utility.
Args:
functions: Functions to compose
Returns:
Composed function
"""
def inner(arg):
result = arg
for func in reversed(functions):
result = func(result)
return result
return inner
## Example usage
def double(x): return x * 2
def increment(x): return x + 1
composed_func = compose(double, increment)
print(composed_func(5)) ## Output: 12
Best Practices
- Keep utilities modular and focused
- Use type hints and docstrings
- Handle potential errors
- Write unit tests for utilities
LabEx recommends practicing these patterns to create robust and reusable utility functions in Python.