Code style - for with if

Which of the three do you think is the best coding style or more readable? foo should be running on elements from both dictionaries, but mydict2 may 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) 
+5
source share
2 answers

Detect the side frame at an early stage and replace it with an empty dict - this is a null object pattern :

 if mydict2 is None: mydict2 = {} 

This is identical to the general pattern used to prevent mutable default arguments. Then you can always have one (very simple) loop:

 for a, b in chain(mydict.items(), mydict2.items()): 

If you are managing the appropriate code, consider changing things so that mydict2 cannot be None in the first place.

+6
source

I like the third option, because a single loop makes the program more understandable. If it were me, I would make an auxiliary generator, in the interests of separation of problems.

 def mydictitems(*dicts): for d in dicts: if d: yield from d.items() for a,b in mydictitems(mydict1, mydict2): foo(a,b) 
+2
source

All Articles