Make sure attribute chains are evaluated safely
Django CI/CD / test (push) Successful in 1m2s Details
Django CI/CD / build-and-push (push) Successful in 2m3s Details

This commit is contained in:
Lukáš Kucharczyk 2024-05-30 11:15:52 +02:00
parent 51c25659a9
commit 28db8ae427
Signed by: lukas
SSH Key Fingerprint: SHA256:vMuSwvwAvcT6htVAioMP7rzzwMQNi3roESyhv+nAxeg
1 changed files with 20 additions and 0 deletions

View File

@ -7,3 +7,23 @@ def safe_division(numerator: int | float, denominator: int | float) -> int | flo
return numerator / denominator
except ZeroDivisionError:
return 0
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.
"""
attrs = attr_chain.split('.')
for attr in attrs:
try:
obj = getattr(obj, attr)
except AttributeError:
return default
return obj