I would really appreciate some insight for rewriting the following functions in a way that it preserves the logic but doesn't throw Sonarlint issues for nested if-else paired with lambda, which I thought was a better way but I guess Sonarlint doesn't think so!! The logic is absolutely correct, the only thing I am trying to figure out is how to remove Sonarlint errors of Cognitive complexity
Part of Function -1
dataframe[f"{col}_KEYWORDS"] = dataframe["FINAL_LABELS"].apply(lambda x, value=col: x[value] if value in x.keys() else None)
dataframe[f"{col}_KEYWORDS"] = dataframe[ f"{col}_KEYWORDS"].apply(lambda x: ', '.join(x) if x is not None else None)
I just want to understand how do I still execute the above logic with conditions without having Sonarlint errors which is too much nested-if else.
Function -2
def _combine_tokens_for_pred(self, pred_argmax_attended_s, tokens_attended_s):
"""
Base function for Predict function
"""
assert len(pred_argmax_attended_s) == len(tokens_attended_s)
model_output = []
error_output = []
for k, pred_argmax_attended in enumerate(pred_argmax_attended_s):
tokens_attended = tokens_attended_s[k]
in_adr = False
per_sentence_adr = []
per_example_adr = []
try:
for i, num in enumerate(pred_argmax_attended):
if num == 2 and in_adr:
in_adr = False
if num == 0:
in_adr = True
if tokens_attended[i][0] == "#":
if len(per_example_adr) > 0:
per_example_adr[-1] += tokens_attended[i][2:]
else:
per_example_adr.append(self._reformat_token(tokens_attended[i]))
if num == 1 and in_adr:
if tokens_attended[i][0] == "#":
per_example_adr[-1] += tokens_attended[i][2:]
else:
per_example_adr.append(self._reformat_token(tokens_attended[i]))
if i < len(pred_argmax_attended) - 1:
if pred_argmax_attended[i + 1] == 2 and in_adr:
per_sentence_adr.append(" ".join(per_example_adr))
in_adr = False
per_example_adr = []
else:
if len(per_example_adr) > 0:
per_sentence_adr.append(" ".join(per_example_adr))
model_output.append("|".join(per_sentence_adr))
except Exception:
error_output.append(k)
model_output.append("")
return model_output, error_output
I have Sonarlint issues for each conditional statement and exception clause, its asking to include certain statements for nesting but I don't want to break the logic. Is there a workaround to this, where I can preserve my logic and rewrite the function in a way to avoid sonar errors.? Thank you in advance :)

