Slide 1: Introduction to Python Utility Functions Utility functions in Python serve as reusable code snippets that perform common operations. They enhance code readability, maintainability, and promote the DRY (Don't Repeat Yourself) principle. This presentation will explore the intricacies of creating, organizing, and optimizing utility functions in Python projects.
Slide 2: Anatomy of a Python Utility Function A well-designed utility function should be:
- Single-purpose
- Pure (no side effects)
- Well-documented
- Easily testable
Example:
def celsius_to_fahrenheit(celsius: float) -> float:
"""
Convert Celsius to Fahrenheit.
Args:
celsius (float): Temperature in Celsius
Returns:
float: Temperature in Fahrenheit
"""
return (celsius * 9/5) + 32Slide 3: Modularization Strategies When creating utility functions, consider:
- Grouping related functions in modules
- Using subpackages for larger collections
- Implementing lazy loading for performance
Example directory structure:
utils/
__init__.py
math_utils.py
string_utils.py
date_utils.py
Slide 4: Performance Considerations Optimize utility functions for performance:
- Use built-in functions and standard library when possible
- Implement caching for expensive operations
- Consider using
functools.lru_cachefor memoization
Example:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n: int) -> int:
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)Slide 5: Testing Utility Functions Implement comprehensive tests for utility functions:
- Use pytest for unit testing
- Cover edge cases and typical use cases
- Implement property-based testing with hypothesis
Example:
import pytest
from hypothesis import given, strategies as st
def is_palindrome(s: str) -> bool:
return s == s[::-1]
@pytest.mark.parametrize("input,expected", [
("radar", True),
("hello", False),
("", True),
])
def test_is_palindrome(input, expected):
assert is_palindrome(input) == expected
@given(st.text())
def test_is_palindrome_property(s):
assert is_palindrome(s + s[::-1])Slide 6: Documentation Best Practices Ensure utility functions are well-documented:
- Use clear and concise docstrings
- Follow PEP 257 conventions
- Include type hints for better IDE support
- Generate API documentation with tools like Sphinx
Example:
from typing import List
def flatten(nested_list: List[any]) -> List[any]:
"""
Flatten a nested list structure.
This function recursively flattens a list that may contain
other lists as elements, returning a single flat list.
Args:
nested_list (List[any]): The nested list to flatten
Returns:
List[any]: A flattened version of the input list
Example:
>>> flatten([1, [2, 3, [4, 5]], 6])
[1, 2, 3, 4, 5, 6]
"""
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_listSlide 7: Python Resources Official Python documentation:
- Python Standard Library: https://docs.python.org/3/library/
- Python Language Reference: https://docs.python.org/3/reference/
- Python HOWTOs: https://docs.python.org/3/howto/
- PEP 8 - Style Guide for Python Code: https://www.python.org/dev/peps/pep-0008/