Accessing value from either os.environ or argparse I have the following code:

#!/usr/bin/env python3
import os, argparse

if __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.verbose


however 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 -v


otherwise False.
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 os
import argparse

if __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.py
Verbose: True
Verbose: True
Verbose: False



Same output as your original.

Other notes:


The comment # Parse arguments. was pointless
Imports should appear on separate lines as per PEP8