Which of the three do you think is a better coding style, or more readable? foo
should be run on the items from both dictionaries, but mydict2
can be None
Option 1:
for a,b in mydict1.items():
foo(a,b)
if mydict2:
for a,b in mydict2.items():
foo(a,b)
Option 2:
for a,b in mydict1.items():
foo(a,b)
for a,b in mydict2.items() if mydict2 else dict().items():
foo(a,b)
Option 3:
for a,b in chain(mydict1.items(), mydict2.items() if mydict2 else dict().items()):
foo(a,b)
Whether you have an else clause or not, it's always there. There always be an else clause. If you believe the above statement is true, leaving out an else clause means either one of these reasons: You don't think about what to do when a condition in an if statement is false .
No, It's not required to write the else part for the if statement. In fact most of the developers prefer and recommend to avoid the else block.
Use the else if statement to specify a new condition if the first condition is false.
Spaces are more common nowadays. One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the tab symbol. For instance, we can align the parameters with the opening bracket, like this: show(parameters, aligned, // 5 spaces padding at the left one, after, another ) { // ... }
Detect the side case early on, and replace it with an empty dict - this is the null object pattern:
if mydict2 is None:
mydict2 = {}
This is identical to a common pattern used to avoid mutable default arguments. Then you can always have one (very simple) loop:
for a, b in chain(mydict.items(), mydict2.items()):
If you control the relevant code, consider changing things so that mydict2
can't be None
in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With