Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code style - for with if

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)
like image 431
yossi Avatar asked Jun 24 '15 08:06

yossi


People also ask

Should there always be else after if?

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 .

Is else if necessary?

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.

What is else if used for?

Use the else if statement to specify a new condition if the first condition is false.

Does javascript use tabs or spaces?

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 ) { // ... }


1 Answers

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.

like image 76
lvc Avatar answered Sep 30 '22 03:09

lvc