MadsRC
MadsRC

Reputation: 139

Several arguments in if statement

I have a script that relies on argparse. The mainbody of the script has if statements like this:

if results.short == True and results.verbose == False and results.verbose2 == False and results.list == False and results.true == False:

Isn't there any shorter way to do that? Say I have more than those 5 arguments, typing each of them in every statement seems like repetitive work.

Can't if do something like:

if results.short == True and "results.%s"== False % (everyotherresults.something):

I'm writing for Python 2.7

Upvotes: 1

Views: 122

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213271

You can use any function on list, and move all your arguments from 2nd in a list: -

if results.short and \
   not any([results.verbose, results.verbose2, results.list, results.true]):

any function returns True if at least one value in the list is True. So, just use not any, which will return True if all the values in the list is False.

And yes, you don't need to compare boolean value with True or False.

Upvotes: 4

SingleNegationElimination
SingleNegationElimination

Reputation: 156188

you shouldn't compare to bool in boolean expressions, eg:

if (results.short 
    and not results.verbose 
    and not results.verbose2 
    and not results.list 
    and not results.true):

Upvotes: 4

Related Questions