I have the following code:#!/usr/bin/env python3import os, argparseif __name__ == '__main__':    # Parse arguments.    parser = argparse.ArgumentParser()    parser.add_argument(-v, --verbose,  action=store_true, dest=verbose)    args = parser.parse_args()    try:        verbose = bool(os.environ['VERBOSE'])    except KeyError:        verbose = args.verbose    print(Verbose:, verbose)And I would like to find the simpler way of returning value from two different sources (either system variable or parsed argument).Ideally I would expect to find some one-liner such as:verbose = bool(os.environ['VERBOSE']) or args.verbosehowever instead I have KeyError exception, therefore I had to implement exception handler.I'm expecting the following tests to print True (if verbose is set):VERBOSE=1 ./test.py./test.py -votherwise False.
Accessing value from either os.environ or argparse
python;error handling
Using get on the os.getenv dictionary and specifying args.verbose as the default value (2nd param of the .get call) will have your desired outcome:import osimport argparseif __name__ == '__main__':    parser = argparse.ArgumentParser()    parser.add_argument(-v, --verbose,  action=store_true, dest=verbose)    args = parser.parse_args()    verbose = bool(os.environ.get('VERBOSE', args.verbose))    print(Verbose:, verbose)Test runs:$ ./test.py -v; VERBOSE=1 ./test.py ; ./test.pyVerbose: TrueVerbose: TrueVerbose: FalseSame output as your original.Other notes:The comment # Parse arguments. was pointlessImports should appear on separate lines as per PEP8