I have an API that returns store availability for an Item, The product should be considered Ready To Purchase if any of the stores return 200, and Not Ready to every other status codes (Including 404).
{
"status": 200,
"sku": "svk__21w",
"store_data": [
{
"status": 404,
"reason": "no product found, or product is not available, or not in inventory"
},
{
"status": 404,
"reason": "no product found, or product is not available, or not in inventory"
},
{
"status": 404,
"reason": "no product found, or product is not available, or not in inventory"
}
]
}
Now, In my code, To check If this product is indeed Ready To Purchase or not, I use a for loop:
is_product_available = False
for store in data['store_data']:
if 'data' in store and store['status'] == 200:
print("Product state is ready to purchase")
is_product_available = True
else:
print("Product state is not ready to purchase")
Which works, But I think it’s just bad design, In the future, With more stores opening..
What I want:
- A better way to check if any of the stores have
dataand their code is200and if so, the product isReady To Purchase.
Example of a Ready To Purchase product:
store_data:
store_1: 404
store_2: 404
store_3 200
Example of a Not Ready To Purchase product:
store_data:
store_1: 404
store_2: 404
store_3 404
>Solution :
You can use the any function
is_product_available = any([store['status'] == 200 for store in data['store_data']])