Environment Variables in Python

Many python scripts require access to external services. API’s for example often require some credentials to be used in order to be able to access the services.

These scripts need to be able to access the credentials somehow. However keeping the credentials directly in the script is not considered best practice.

A well established way of allowing programs access to credentials is through the use of environment variables.

Environment variables are variables that exist in the system and are available to software programs that are run.

Enter python-dotenv, a python package that allows for easy access of environment variables.

The python-dotenv package can be found on pypi here: https://pypi.org/project/python-dotenv/

The python-dotenv package can be used to load values into environment variables that are in a .env file in the same directory

python script:

from dotenv import load_dotenv
import os

# load values from .env to environment

# assign the value of environment variable 'KEY' to the variable key
key = os.getenv("KEY")

file: ‘.env’


Running the python script will now result in the variable key having the value ‘a_super_secret_key_code’.

With credentials now separated from the python script we are free to share the python script without the world knowing our passwords and credentials.

Send a Comment

Your email address will not be published.