Getting Environment Variables

1. Getting Environment Variable

To get the value of an environment variable in python, we need a key.

For example our key is DEBUG which might tell us if the application is running in debug mode.

import os

is_debug = os.getenv('DEBUG')

The key must match here.

Our variable is_debug will now contain the value from our environment variabl.

2. Include Default Value

What if the environment variable we are looking for does not exist in the system? Our operation will return a null value or in python it's None. Most of the time we don't want that behaviour.

So the solution is to set a default value just in case.

To this is very straightforward.

import os

is_debug = os.getenv('DEBUG', True)

That's it for this topic, have a great one!

Last Updated:
Contributors: alexiusacademia