Reputation: 43
I have a program that begins by parsing several arguments, one of which is a "verbose" flag. However, I also have a "simulate" flag, which I would like to automatically flip the verbose flag to "True" if it is on.
Right now I have this working:
if args.verbose or simulate:
verbose = True
How can I get this onto one line? I was expecting to be able to do something like:
verbose = True if args.verbose or simulate
or like:
verbose = True if (args.verbose or simulate)
While searching here, I found a solution that fits on one line:
verbose = (False, True)[args.verbose or simulate]
However, I find that solution to be much less readable than the others that I was hoping would work. Is this possible, and I'm just missing something? Or is it not possible to use an "or" between two checks for "True" like this in one line?
Upvotes: 2
Views: 646
Reputation: 477160
A functionally equivalent expression would be:
verbose = True if args.verbose or simulate else verbose
since it is possible that verbose
is already True
, or something else (a number, a list, a dictionary, etc.)
Furthermore if we are not sure arg.verbose
and simulate
are booleans, we can not use:
verbose = arg.verbose or simulate
since if for example simulate
is [1]
, then we get:
>>> False or [1]
[1]
We can however convert this expression to a boolean, like:
verbose = bool(arg.verbose or simulate) or verbose
here in case the condition is False
, we assign verbose
back to verbose
(since again it is possible that verbose
has been set to something other than False
).
If however both simulate and verbose
are known to be booleans, we can use:
verbose = arg.verbose or simulate or verbose
In case it is known that verbose
has been set to False
initially:
verbose = arg.verbose or simulate
is sufficient. In that case we can skip the previous initialization of verbose
(given it is not used between the initialization and setting it here).
Upvotes: 1
Reputation: 361849
The problem isn't with or
, it's that you need an else
clause to specify what the value should be if the if
statement fails. Otherwise, what is getting assigned if the condition is false?
verbose = True if args.verbose or simulate else False
There's no need for the if
at all, though. It's even simpler if you just assign the result of the test to verbose
directly:
verbose = args.verbose or simulate
Upvotes: 5