How to check list of environment variable in python? I have requirement to check list of environment variable in Linux. Based on environment variable, exit code will be different. how to optimize the below code?

def check_mandatory_envs():
    if "ENVCONTEST_1" not in os.environ:
        exit(125)
    if "ENVCONTEST_2" not in os.environ:
        exit(126)
    if "ENVVIRTEST_3" not in os.environ
        exit(127)
    if "ENVVIRTEST_4" not in os.environ
        exit(128)
    if "ENVPATHTEST_5" not in os.environ
        exit(129)
    if "ENVPATHTEST_6" not in os.environ
        exit(130)
You can group the messages and corresponding exit codes into a dict, and then iterate over that one:

def check_mandatory_envs():
    exit_codes = {
        "ENVCONTEST_1" :125,
        "ENVCONTEST_2" :126,
        "ENVVIRTEST_3" :127,
        "ENVVIRTEST_4" :128,
        "ENVPATHTEST_5":129,
        "ENVPATHTEST_6":130,
    }
    for variable, code in exit_codes.items():
        if variable not in os.environ:
            exit(code)


If the order of the iteration is important and you are on python before 3.6, you canuse a collections.OrderedDict or a list of tuples, without the .items() call