I have the following snippets, among which I cannot find the clear winner. Which style would you recommend? Is there anything better than these?
(assuming self.task.flags is a dictionary)
inand[]if 'target_names' in self.task.flags: foo(self.task.flags['target_names'])This mentions the names of the dictionary and the key twice (violating DRY).
I can also imagine that this does the identical lookup twice internally, throwing away the value in the first case (
in).getand temporary variablevalue = self.task.flags.get('target_names') if value: foo(value)This removes the repetition, but a temporary variable is not very elegant.
The meaning is also subtly different from the others, when
{'target_names': None}is present inself.task.flags.exceptions ("EAFP")
try: foo(self.task.flags['target_names']) except KeyError: passI hear that EAFP is generally encouraged in Python, but I still fear that exceptions can be expensive, especially when the chance of the key being present is not very high.
This may also mask any exceptions raised inside
foo.And the
try…exceptstructure can be visually distracting; even more when other exception handling is involved.
ugly way: