Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:       ....... 
like image 530
Riccardo Califano Avatar asked Jul 27 '20 13:07

Riccardo Califano


People also ask

How do you check a boolean variable in Python?

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.

Can env variables be boolean?

Again, since environment variables hold strings, we cannot use boolean values.

How do you assign a boolean value to a variable in Python?

The bool() method in Python returns a boolean value and can be used to cast a variable to the type Boolean.


2 Answers

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

like image 147
Rui Martins Avatar answered Sep 19 '22 07:09

Rui Martins


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

like image 22
Arek S Avatar answered Sep 21 '22 07:09

Arek S