|
| 1 | +""" |
| 2 | +Utility functions for safe operations and value handling. |
| 3 | +
|
| 4 | +Provides defensive programming utilities for common operations that may encounter |
| 5 | +None values, invalid inputs, or edge cases. Includes safe arithmetic operations, |
| 6 | +attribute access, and timestamp formatting. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from datetime import datetime |
| 12 | +from typing import Any |
| 13 | + |
| 14 | +__all__ = [ |
| 15 | + "all_defined", |
| 16 | + "safe_add", |
| 17 | + "safe_divide", |
| 18 | + "safe_format_timestamp", |
| 19 | + "safe_getattr", |
| 20 | + "safe_multiply", |
| 21 | +] |
| 22 | + |
| 23 | + |
| 24 | +def safe_getattr(obj: Any | None, attr: str, default: Any = None) -> Any: |
| 25 | + """ |
| 26 | + Safely get an attribute from an object with None handling. |
| 27 | +
|
| 28 | + :param obj: Object to get the attribute from, or None |
| 29 | + :param attr: Name of the attribute to retrieve |
| 30 | + :param default: Value to return if object is None or attribute doesn't exist |
| 31 | + :return: Attribute value or default if not found or object is None |
| 32 | + """ |
| 33 | + if obj is None: |
| 34 | + return default |
| 35 | + |
| 36 | + return getattr(obj, attr, default) |
| 37 | + |
| 38 | + |
| 39 | +def all_defined(*values: Any | None) -> bool: |
| 40 | + """ |
| 41 | + Check if all provided values are defined (not None). |
| 42 | +
|
| 43 | + :param values: Variable number of values to check for None |
| 44 | + :return: True if all values are not None, False otherwise |
| 45 | + """ |
| 46 | + return all(value is not None for value in values) |
| 47 | + |
| 48 | + |
| 49 | +def safe_divide( |
| 50 | + numerator: int | float | None, |
| 51 | + denominator: int | float | None, |
| 52 | + num_default: float = 0.0, |
| 53 | + den_default: float = 1.0, |
| 54 | +) -> float: |
| 55 | + """ |
| 56 | + Safely divide two numbers with None handling and zero protection. |
| 57 | +
|
| 58 | + :param numerator: Number to divide, or None to use num_default |
| 59 | + :param denominator: Number to divide by, or None to use den_default |
| 60 | + :param num_default: Default value for numerator if None |
| 61 | + :param den_default: Default value for denominator if None |
| 62 | + :return: Division result with protection against division by zero |
| 63 | + """ |
| 64 | + numerator = numerator if numerator is not None else num_default |
| 65 | + denominator = denominator if denominator is not None else den_default |
| 66 | + |
| 67 | + return numerator / (denominator or 1e-10) |
| 68 | + |
| 69 | + |
| 70 | +def safe_multiply(*values: int | float | None, default: float = 1.0) -> float: |
| 71 | + """ |
| 72 | + Safely multiply multiple numbers with None handling. |
| 73 | +
|
| 74 | + :param values: Variable number of values to multiply, None values treated as 1.0 |
| 75 | + :param default: Starting value for multiplication |
| 76 | + :return: Product of all non-None values multiplied by default |
| 77 | + """ |
| 78 | + result = default |
| 79 | + for val in values: |
| 80 | + result *= val if val is not None else 1.0 |
| 81 | + return result |
| 82 | + |
| 83 | + |
| 84 | +def safe_add( |
| 85 | + *values: int | float | None, signs: list[int] | None = None, default: float = 0.0 |
| 86 | +) -> float: |
| 87 | + """ |
| 88 | + Safely add multiple numbers with None handling and optional signs. |
| 89 | +
|
| 90 | + :param values: Variable number of values to add, None values use default |
| 91 | + :param signs: Optional list of 1 (add) or -1 (subtract) for each value. |
| 92 | + If None, all values are added. Must match length of values. |
| 93 | + :param default: Value to substitute for None values |
| 94 | + :return: Result of adding all values safely (default used when value is None) |
| 95 | + """ |
| 96 | + if not values: |
| 97 | + return default |
| 98 | + |
| 99 | + values = list(values) |
| 100 | + |
| 101 | + if signs is None: |
| 102 | + signs = [1] * len(values) |
| 103 | + |
| 104 | + if len(signs) != len(values): |
| 105 | + raise ValueError("Length of signs must match length of values") |
| 106 | + |
| 107 | + result = values[0] if values[0] is not None else default |
| 108 | + |
| 109 | + for ind in range(1, len(values)): |
| 110 | + val = values[ind] if values[ind] is not None else default |
| 111 | + result += signs[ind] * val |
| 112 | + |
| 113 | + return result |
| 114 | + |
| 115 | + |
| 116 | +def safe_format_timestamp( |
| 117 | + timestamp: float | None, format_: str = "%H:%M:%S", default: str = "N/A" |
| 118 | +) -> str: |
| 119 | + """ |
| 120 | + Safely format a timestamp with error handling and validation. |
| 121 | +
|
| 122 | + :param timestamp: Unix timestamp to format, or None |
| 123 | + :param format_: Strftime format string for timestamp formatting |
| 124 | + :param default: Value to return if timestamp is invalid or None |
| 125 | + :return: Formatted timestamp string or default value |
| 126 | + """ |
| 127 | + try: |
| 128 | + return datetime.fromtimestamp(timestamp).strftime(format_) |
| 129 | + except (ValueError, TypeError, OverflowError, OSError): |
| 130 | + return default |
0 commit comments