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: .......
We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.
Again, since environment variables hold strings, we cannot use boolean values.
The bool() method in Python returns a boolean value and can be used to cast a variable to the type Boolean.
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
All the same, but thats the most readable version for me:
DEBUG = (os.getenv('DEBUG', 'False') == 'True')
Here anything but True
will evaluate to False. DEBUG is False unless explicitly set to True
in ENV
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With