2023-11-09 09:06:14 +00:00
|
|
|
def safe_division(numerator: int | float, denominator: int | float) -> int | float:
|
|
|
|
"""
|
|
|
|
Divides without triggering division by zero exception.
|
|
|
|
Returns 0 if denominator is 0.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return numerator / denominator
|
|
|
|
except ZeroDivisionError:
|
|
|
|
return 0
|
2024-06-03 16:19:11 +00:00
|
|
|
|
|
|
|
|
2024-05-30 09:15:52 +00:00
|
|
|
def safe_getattr(obj, attr_chain, default=None):
|
|
|
|
"""
|
|
|
|
Safely get the nested attribute from an object.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
obj (object): The object from which to retrieve the attribute.
|
|
|
|
attr_chain (str): The chain of attributes, separated by dots.
|
|
|
|
default: The default value to return if any attribute in the chain does not exist.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The value of the nested attribute if it exists, otherwise the default value.
|
|
|
|
"""
|
2024-06-03 16:19:11 +00:00
|
|
|
attrs = attr_chain.split(".")
|
2024-05-30 09:15:52 +00:00
|
|
|
for attr in attrs:
|
|
|
|
try:
|
|
|
|
obj = getattr(obj, attr)
|
|
|
|
except AttributeError:
|
|
|
|
return default
|
|
|
|
return obj
|