I'm having concerns about readability of this piece of code:

messages_dict = {'error':errors, 'warning':warnings}[severity]
messages_dict[field_key] = message

and I'm to use this instead:

if severity == 'error':
    messages_dict = errors
elif sevierty == 'warning':
    messages_dict = warnings
    raise ValueError('Incorrect severity value')
messages_dict[field_key] = message

But it looks too verbose for such a simple thing.

I don't care too much if it's more efficient than constructing a dictionary for just two mappings. Readability and maintainability is my biggest concern here (errors and warnings are method arguments, so I cannot build the lookup dictionary beforehand and reuse it later).

  • \$\begingroup\$ I don't see the readability concern with the first case. \$\endgroup\$ – Latty Jan 25 '13 at 14:43
  • \$\begingroup\$ I thought that it might puzzle an unaware reader... \$\endgroup\$ – fortran Jan 25 '13 at 14:52
  • \$\begingroup\$ Unaware of what? Dictionaries? They are a core Python data structure - if someone can't read that, they don't know Python. You can't write code that is readable for someone who have no idea. \$\endgroup\$ – Latty Jan 25 '13 at 15:08
  • \$\begingroup\$ I meant unaware of the 'pattern' (using a dict to choose between two options). I've seen complaints in peer reviews about using boolean operators in a similar way (like x = something or default, maybe a little bit more complex) because it was obscure :-/ \$\endgroup\$ – fortran Jan 25 '13 at 17:21
  • \$\begingroup\$ That's a different situation, as it's relatively unclear what is going on (and is better replaced by the ternary operator). This isn't particularly a pattern, it's just a use of dictionaries. \$\endgroup\$ – Latty Jan 26 '13 at 14:14

Since you mention maintainability I think that the consideration can be taken in terms of what next changes may look like. If further changes will take more statements to be executed with the result of one of those specific options, or if more options will be added, I would stick to the dictionary approach.

Looking into the future can certainly be tricky, but you need to also think how much will the code need to be change to assert a specific new need. If you need to add a new level of reporting, would you prefer to add a new else if or just a value in a dictionary?

Readability then starts to backfire, since if ... else is quite common. What happens when you arrive at 3, 4 or 5 branches?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.