How to Set and Get Environment Variables in Python

1 min read

Environment variables are useful when you want to avoid hardcoding certain parts of your 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.

To set and get environment variables in Python is the same as working with dictionaries. You just need to import the os module.

import os  # Set environment variables

os.environ['EMAIL_USER'] = 'user@example.com' os.environ['EMAIL_PASSWORD'] = 'aeb72hasow82ajl'

# Retrieve set environment variables USER = os.environ.get('EMAIL_USER') # USER is now set to 'user@example.com' PASSWORD = os.environ.get('EMAIL_PASSWORD') # PASSWORD is now set to 'aeb72hasow82ajl'

# Retrieving non-existent keys FOO = os.environ.get('FOO') # FOO is set to None. BAR = os.environ['BAR'] # Raises a KeyError as key does not exist.

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

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 can just refer to their documentation.


Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett
Python

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter