python-3.xif-statementboolean

Evaluate boolean environment variable in Python


How can I evaluate if a env variable is a boolean True, in Python? Is it correct to use:

if os.environ['ENV_VAR'] is True:
      .......

Solution

  • Option 1

    I think this works well:

    my_env = os.getenv("ENV_VAR", 'False').lower() in ('true', '1', 't')
    

    It allows: things like true, True, TRUE, 1, "1", TrUe, t, T, ...

    Update: After I read the commentary of Klaas, I updated the original code my_env = bool(os.getenv(... to my_env = os.getenv(... because in will result in a bool type


    Option 2

    UPDATE: After the @MattG commentary, I added a new solution that raises an error for entries like ttrue instead of returning False:

    # ...
    import os
    # ...
    
    def get_variable(name: str, default_value: bool | None = None) -> bool:
        true_ = ('true', '1', 't')  # Add more entries if you want, like: `y`, `yes`, `on`, ...
        false_ = ('false', '0', 'f')  # Add more entries if you want, like: `n`, `no`, `off`, ...
        value: str | None = os.getenv(name, None)
        if value is None:
            if default_value is None:
                raise ValueError(f'Variable `{name}` not set!')
            else:
                value = str(default_value)
        if value.lower() not in true_ + false_:
            raise ValueError(f'Invalid value `{value}` for variable `{name}`')
        return value in true_
    
    # ...
    
    my_env1 = get_variable("ENV_VAR1")
    my_env2 = get_variable(name="ENV_VAR2") # Raise error if variable was not set
    my_env3 = get_variable(name="ENV_VAR3", default_value=False) # return False if variable was not set