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
= data.get("key") # Example: Extract value for "key"
extracted_value 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
f"Data extraction failed: {e}")
warnings.warn(return ""
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
= {"key": "value"}
data print(complex_fn(data))
value
= {"another_key": "value"}
data_missing 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.WARNING, format="%(asctime)s - %(levelname)s - %(message)s")
logging.basicConfig(level
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
= data.get("key") # Example: Extract value for "key"
extracted_value 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
f"Data extraction failed: {e}")
logging.warning(return ""
= {"key": "value"}
data print(complex_fn(data))
value
= {"another_key": "value"}
data_missing print(complex_fn(data_missing))
2024-11-23 11:43:51,261 - WARNING - Data extraction failed: Key not found in data.