From 28db8ae42782218cb357dc4095ea40732791a061 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= Date: Thu, 30 May 2024 11:15:52 +0200 Subject: [PATCH] Make sure attribute chains are evaluated safely --- common/utils.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/common/utils.py b/common/utils.py index 422a018..f837ec0 100644 --- a/common/utils.py +++ b/common/utils.py @@ -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