如何提高嵌套if和for语句的可读性

时间:2012-04-10 07:34:12

标签: python for-loop refactoring

我有一个非常讨厌的代码我想重构但是因为它完全不可读。

 for region in feed['config']['regions']:
            if region['region'] == region_name:
                for instance_type in region['instanceTypes']:
                    if instance_type['type'] == instance_type_name:
                        for instance_size in instance_type['sizes']:
                            if instance_size['size'] == instance_size_name:
                                for platform in instance_size['valueColumns']:
                                    if platform['name'] == platform_name:
                                        prices = platform['prices']
                                        assert prices.keys() == ['USD']
                                        return decimal.Decimal(prices['USD'])
        assert False, "Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" % \
                (region_name, instance_type_name, instance_size_name, platform_name)

我已经考虑过在每个循环或if语句中使用函数,但这会给我一大堆函数。 是否有更好的解决方案?

2 个答案:

答案 0 :(得分:6)

try:
    region = [r for r in feed['config']['regions'] if region['region'] == region_name][0]
    instance_type = [t for t in region['instanceTypes'] if i['type'] == instance_type_name][0]
    # ...
    return decimal.Decimal(prices['USD'])
except IndexError:
    raise Exception("Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" % 
                (region_name, instance_type_name, instance_size_name, platform_name))

或更进一步:

def filter_by_key(key, value, objects):
    return [o for o in objects if region[key] == value][0]

try:
    region = filter_by_key('region', region_name, feed['config']['regions'])
    instance_type = filter_by_key('type', instace_type_name, region['instanceTypes'])
    # ...
    return decimal.Decimal(prices['USD'])
except IndexError:
    raise Exception("Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" % 
                (region_name, instance_type_name, instance_size_name, platform_name))

答案 1 :(得分:2)

如果您想将其保持在循环中,可以使用continue来保存缩进:

for region in feed['config']['regions']:
    if region['region'] != region_name: continue
    for instance_type in region['instanceTypes']:
        if instance_type['type'] != instance_type_name: continue
        for instance_size in instance_type['sizes']:
            if instance_size['size'] != instance_size_name: continue
            for platform in instance_size['valueColumns']:
                if platform['name'] != platform_name: continue
                prices = platform['prices']
                assert prices.keys() == ['USD']
                return decimal.Decimal(prices['USD'])
assert False, "Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" % \
                (region_name, instance_type_name, instance_size_name, platform_name)

或者列表推导:

regions = (r for r in feed['config']['regions'] if r['region'] == region_name)
instance_types = (i for i in r['instanceTypes'] for r in regions if i['type'] == instance_type_name)
instance_sizes = (i for i in t['sizes'] for t in instance_types if i['size'] == instance_size_name)
platforms = (p for p in s['valueColumns'] for s in instance_sizes if p['name'] == platform_name)
for platform in platforms:
    prices = platform['prices']
    assert prices.keys() == ['USD']
    return decimal.Decimal(prices['USD'])
assert False, "Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" % \
                (region_name, instance_type_name, instance_size_name, platform_name)