The problem
Imagine two services running:
Service 1 has two statuses: ACTIVE/INACTIVE
Service 2 has two statuses: RUNNING/TERMINATED
We want to do a simple status comparison as:
service1_status = get_service2_status()
service2_status = get_service2_status()
if service1_status == service2_status:
// They match!
else:
// They don't match!
A working solution
This is a relatively simple task of course. A working solution would be something like this:
service1_status = get_service2_status()
service2_status = get_service2_status()
if service1_status == 'ACTIVE' and service2_status == 'RUNNING':
return "They match!"
elif service1_status == 'INACTIVE' and service2_status == 'TERMINATED':
return "They match!"
else:
return "They don't match!"
The problem – but more difficult
Now imagine this example a hundred different statuses for each service instead of two.
The if statement would be overwhelming. I am looking for a more elegant way to program this. e.g:
matching_tuples = [('x1', 'y1'), ('x2', 'y2'), ..., ('x100', 'y100')]
service1_status = get_service2_status()
service2_status = get_service2_status()
if (service1_status, service2_status) in matching_tuples:
return "They match!"
elif:
return "They don't match!"
This works and is fine. I wonder though if there is a better, more pythonic and elegant way to marry two strings together and compare them.
>Solution :
I also have to map keys from the backend and frontend.
For mapping, I usually use a dictionary you can add as many keys as you want like this.
MapService1to2 = {
"ACTIVE": "RUNNING",
"INACTIVE": "TERMINATED"
}
service1_status = get_service2_status()
service2_status = get_service2_status()
if MapService1to2[service1_status] == service2_status:
print("They match")
else:
print("They don't match")