# How to Set and Get Environment Variables in Python

To set and get environment variables in Python you can just use the os module:

import os

# Set environment variables
os.environ['API_USER'] = 'username'
os.environ['API_PASSWORD'] = 'secret'

# Get environment variables
USER = os.getenv('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')

# Getting non-existent keys
FOO = os.getenv('FOO') # None
BAR = os.environ.get('BAR') # None
BAZ = os.environ['BAZ'] # KeyError: key does not exist.


Note that using getenv() or the get() method on a dictionary key will return None if the key does not exist. However, in the example with BAZ, if you reference a key in a dictionary that does not exist it will raise a KeyError.

Environment variables are useful when you want to avoid hard-coding access credentials or other variables into code. For example, you may need to pass in API credentials for an email service provider in order to send email notifications but you wouldn’t want these credentials stored in your code repository. Or perhaps you need your code to function slightly differently between your development, staging and production environments. In this case you could pass in an environment variable to tell your application what environment it’s running in. These are typical use cases for environment variables.

## Storing local env variables

You should write your Python code so that it is able to access environment variables from whatever environment it is running in. This could be either your local virtual environment that you’re using for development or a service that you are hosting it on. A useful package that simplifies this process is Python Decouple, this is how you would use it.

First install Python Decouple into your local Python environment.

$pip install python-decouple  Once installed, create a .env file in the root of your project which you can then open up to add your environment variables. $ touch .env   # create a new .env file
\$ nano .env    # open the .env file in the nano text editor


‌You can then add your environment variables like this:

USER=alex
KEY=hfy92kadHgkk29fahjsu3j922v9sjwaucahf


Then save (WriteOut) the file and exit nano. Your environment variables are now stored in your .env file. If you’re using git, remember to add .env to your .gitignore file so that you don’t commit this file of secrets to your code repository.

Now that you have your environment variables stored in a .env file, you can access them in your Python code like this:

from decouple import config

API_USERNAME = config('USER')
API_KEY = config('KEY')


The benefit of using something like the above approach is that when you deploy your application to a cloud service, you can set your environment variables using whatever method or interface the provider has and your Python code should still be able to access them. Note that it is common convention to use capital letters for names of global constants in your code.

Most cloud service providers will have a CLI or web interface that lets you configure the environment variables for your staging or production environments. For guidance in these cases you ‘ll need to refer to their documentation on how to set environment variables when using their service.

Join the Able Developer Network

If you liked this post you might be interested in the Able developer network, a new place for developers to blog and find jobs.

But better to use os.getenv

Thanks for the tip, Dmitry! Have updated.

Hi, Dmitry!

Do you know what's the difference between using os.environ.get and os.getenv? Is there any efficiency difference or you choose it because it's shorter?

Thanks!

There is good out of the box Python solution called pycrosskit. It will create environment variables that are persistent both for Linux and Windows.

Usage:

# Will Set Persistent Value for Variable in System
# * subkey works only for windows like file in folder
# * reg_path works only for windows as register path
SysEnv.set_var(name, value, subkey, reg_path=default_reg_path)

# Will Get Persistent Value for Variable in System
# * reg_path works only for windows as register path
# * delete, deletes key from environment and its subkeys after read
SysEnv.get_var(name, reg_path=default_reg_path, delete=False)


Great explanation! Thank you so much!

Really nice and simple solution, it is not necessary to install the command direnv or anything else, Thanks!

Thanks a lot Rhett for yout post. I actually was looking for a method that combines the usage of a .env and the environment variables.

Thanks a lot for the very useful information. The environment variable that I have created using this information is available within the current script only. I mean it is not available in new console (i.e. it is not available for other applications).

Is it possible doing it as well?

Hi Sergei, I've updated the article with a bit more information on how to store env variables locally. Hope this helps.

Nice post - fixed my problem!

You don't explain how to set them

Just use os.system to invoke the shell command to set the variable.