if a == arg:
if arg not in a_list:
do_something(arg)
elif b == arg:
if arg not in b_list:
do_something(arg)
else:
do_something_else(arg)
Propose an idiomatic way to shorten and specifically DRY above statements – without extracting parts of it to separate functions.
edit: Funny 😉 This not a homework assignment neither is this a request to review my code, perhaps if I reframe above as below my intentions become more clear:
What is a pythonian way to write above if-statements such that it is both DRY and idiomatic to the language? I feel I am missing something, perhaps one can make use of the and/or operators in python? Reason for not extracting any parts of it to separate functions is that then this question is more about refactoring than about idiomatic pythonian if-logic.
Here is a simple answer:
Combining the
a, anda_listandb, andb_listinto tuples, we can easier iterate them.Then its a simple matter of the iteration itself, matching the conditions, and running the desired function..
Python supports
for....elsestatements.The else statement will run if there are no returns or breaks in the for loop.
Here, if we get our desired match, the loop will break, and we are done. if we never break, then we get to our else loop. In my opinion this is the most Pythonic way to do this.
Edit
To make this any better, you should have
a, b, a_list, b_listinside some kind of dictionary, whered[a] = a_listThen you could just iterate over the dict like this:
It’s almost the same thing, but it looks nicer, and you can have all your
a‘s andb‘s and lists all sorted out before hand.