Pergunta

Trying not to use too many variables in code, I came up with the code below. It looks horrible. Any ideas on how to format it nicely? Do I need to use more variables?

I write code like this a lot, and it'd help to see what methods people usually resort to have readable code while making creating less variables

exceptions = []

# find all the distinct parent exceptions (sorted) and add to the list
#   with their children list
for parent in collection.find(
    {'tags': 'exception'}).sort('viewPriority').distinct('parentException'):
    group_info = {'groupName': parent,
                  'children': [{'value': ex['value'],
                                'label': ex['label'],}
        for ex in collection.find({'tags': 'exception',
                                   'parentException': parent}
                                 ).sort('viewPriority')],
                 }
    exceptions.append(group_info)
Foi útil?

Solução

I would break your logic up into functions

def get_children(parent):
    result = collection.find({'tags': 'exception', 'parentException': parent})
    result = result.sort('viewPriority')
    return [{'value': ex['value'], 'label': ex['label']} for ex in result]

def get_group_info(parent):     
    return {'groupName': parent, 'children': get_children(parent)}

result = collection.find({'tags': 'exception'})
result = result.sort('viewPriority').distinct('parentException')

exceptions = [get_group_info(parent) for parent in result]

As a bonus, you can easily unittest get_children and get_group_info

Outras dicas

Definitely difficult to get this to look any good, here is my best attempt at keeping the line lengths short and maintaining readability:

exceptions = []

# find all the distinct parent exceptions (sorted) and add to the list
#   with their children list
for parent in (collection.find({'tags': 'exception'})
               .sort('viewPriority').distinct('parentException')):
    group_info = {
        'groupName': parent,
        'children': [{'value': ex['value'], 'label': ex['label'],}
                     for ex in (collection.find({'tags': 'exception',
                                                 'parentException': parent})
                                .sort('viewPriority'))],
    }
    exceptions.append(group_info)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top