1
\$\begingroup\$

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)
\$\endgroup\$
3
  • \$\begingroup\$ Where does exit(...) come from? Are you using something like from sys import exit at the beginning of your script? \$\endgroup\$
    – AlexV
    Nov 18 '19 at 15:22
  • \$\begingroup\$ @AlexV exit is a builtin as far as I know. \$\endgroup\$
    – JAD
    Nov 18 '19 at 15:35
  • 3
    \$\begingroup\$ @JAD It is, but there are noticeable differences between calling exit, sys.exit, and os.exit. \$\endgroup\$
    – AlexV
    Nov 18 '19 at 15:38
4
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Is there an advantage of using a dictionary here compared to, say, a tuple of tuples or something similar? \$\endgroup\$
    – AlexV
    Nov 18 '19 at 15:42
  • 1
    \$\begingroup\$ Not really, there is no real downside either as far as I know. This also conveys that a certain variable has one exit code, and it throws a SyntaxError at compile time if you forgot an exit code or a comma, making input errors easier to find. \$\endgroup\$ Nov 18 '19 at 15:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.