简体   繁体   中英

Is there a way to simplify assignment to variable with multiple conditions?

I'm writing a python script to build my code. The script can run in one of two modes: debug and optimized. The mode can be set by the command line arguments --debug and --optimized . Only one of those arguments can be given. That is, you can't do:

python build.py --debug --optimized # command usage error

Furthermore, if no arguments are given, the script defaults to use the DEBUG setting in my configuration file.

Here are examples of how the script might be called:

python build.py --debug build in debug mode.
python build.py --optimized build in optimized mode.
python build.py use debug setting from config file.

Here's a simplified version of the code I use to set the debug mode:

if options["debug"]:
    debug = True  # --debug was given
elif options["optimized"]:
    debug = False  # --optimized was given
else:
    debug = settings.DEBUG  # use DEBUG from config file

Although it works, I feel like there is a way to simplify this code. I know about conditional assignments in python but I couldn't think how it would work here.

How would you simplify this code to make it shorter or more readable? Or perhaps it's already as simplified as it can get?

I'm using python 3.7 so any python 3 only trick would be acceptable as well.

One way would be to switch to one-liners and do it in reverse order (with later assignments overriding earlier ones):

debug = settings.DEBUG                  # normal state.
if options["optimized"]: debug = False  # optimised overrides default
if options["debug"]:     debug = True   # debug overrides default AND optimised

This doesn't actually cover the "error" condition where you specify both "optimised" and "debug" but often it's far simpler just to let one have priority over the other.

If you really want to catch the error condition, you could have a pre-check before the two if statements, such as:

if options["optimized"] and options["debug"]:
    raiseSomeSortOfErrorCondition()

But, based on your comment that this will never happen (as argparse prevents it), it's probably not necessary. You may want to consider adding a comment to that effect so as to make it clear it cannot happen but the code itself doesn't really need to change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM