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:
.......
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
UPDATE:
After the @MattG commentary, I added a new solution that raises an error for entries like ttrue
instead of returning False
:
# ...
import os
# ...
TRUTHY_VALUES = ('true', '1', 't') # Add more entries if you want, like: `y`, `yes`, `on`, ...
FALSY_VALUES = ('false', '0', 'f') # Add more entries if you want, like: `n`, `no`, `off`, ...
VALID_VALUES = TRUTHY_VALUES + FALSY_VALUES
def get_bool_env_variable(name: str, default_value: bool | None = None) -> bool:
value = os.getenv(name) or default_value
if value is None:
raise ValueError(f'Environment variable "{name}" is not set!')
value = str(value).lower()
if value not in VALID_VALUES:
raise ValueError(f'Invalid value "{value}" for environment variable "{name}"!')
return value in TRUTHY_VALUES
# ...
my_env1 = get_bool_env_variable('ENV_VAR1') # Raise error if variable was not set
my_env2 = get_bool_env_variable('ENV_VAR2', default_value=False) # return False if variable was not set