15  Try-fails-NA

15.1 Try, fails -> return missing

Try do something, if fails, return missing value, and log the warning message. No error is thrown.

15.1.1 Use warnings.warn

import warnings


def complex_fn(data):
    """
    A function to extract data with error handling.
    If data extraction fails, returns a missing value ("") and logs a warning.
    """
    try:
        # Simulate data extraction logic
        extracted_value = data.get("key")  # Example: Extract value for "key"
        if extracted_value is None:
            raise ValueError("Key not found in data.")
        return extracted_value
    except Exception as e:
        # Log the warning and return missing value
        warnings.warn(f"Data extraction failed: {e}")
        return ""
data = {"key": "value"}
print(complex_fn(data))  
value
data_missing = {"another_key": "value"}
print(complex_fn(data_missing)) 
/var/folders/70/7wmmf6t55cb84bfx9g1c1k1m0000gn/T/ipykernel_64621/2471619121.py:17: UserWarning: Data extraction failed: Key not found in data.
  warnings.warn(f"Data extraction failed: {e}")

15.1.2 Use logging

import logging

# Configure logging
logging.basicConfig(level=logging.WARNING, format="%(asctime)s - %(levelname)s - %(message)s")

def complex_fn(data):
    """
    A function to extract data with error handling.
    If data extraction fails, returns a missing value ("") and logs a warning.
    """
    try:
        # Simulate data extraction logic
        extracted_value = data.get("key")  # Example: Extract value for "key"
        if extracted_value is None:
            raise ValueError("Key not found in data.")
        return extracted_value
    except Exception as e:
        # Log the warning and return missing value
        logging.warning(f"Data extraction failed: {e}")
        return ""
data = {"key": "value"}
print(complex_fn(data))  
value
data_missing = {"another_key": "value"}
print(complex_fn(data_missing)) 
2024-11-23 11:43:51,261 - WARNING - Data extraction failed: Key not found in data.