I have a working function with too many if/else statements (pylint). The code works but it's not good. I try to improve it but I have some tunnelvision. Can someone help me to improve the code?
So depending on a list of stacks, an environment (prod, nonprod or all) and a list of account IDs there can be filtered on which stacks need to be updated.
This is an example of a stack dict:
{'AccountId': '123456789101', 'StackName': 'test-nonprod'}
function:
def filter_stacks(stacks, environment, account_ids):
"""todo"""
non_prod_regex = re.compile("(nonprod|non-prod)")
stacks_to_update = []
if non_prod_regex.match(environment) and account_ids:
for stack in stacks:
if (
non_prod_regex.search(stack["StackName"])
and stack["AccountId"] in account_ids
):
stacks_to_update.append(stack)
elif non_prod_regex.match(environment) and not account_ids:
for stack in stacks:
if non_prod_regex.search(stack["StackName"]):
stacks_to_update.append(stack)
elif re.compile("all").match(environment) and account_ids:
for stack in stacks:
if stack["AccountId"] in account_ids:
stacks_to_update.append(stack)
elif re.compile("all").match(environment) and not account_ids:
stacks_to_update = stacks
elif not non_prod_regex.match(environment) and account_ids:
for stack in stacks:
if (
not non_prod_regex.search(stack["StackName"])
and stack["AccountId"] in account_ids
):
stacks_to_update.append(stack)
elif not non_prod_regex.match(environment) and not account_ids:
for stack in stacks:
if not non_prod_regex.search(stack["StackName"]):
stacks_to_update.append(stack)
else:
print("No match found.")
return stacks_to_update