Leveraging the .env file in Python

Safely store sensitive information in this file, like your API keys and tokens.

Whenever you’re programming, you may have some secret “codes”, such as your OpenAI key or Amazon AWS S3 bucket key.

When checking sensitive information into source control (such as Git), you do not want to include this in your code since it could get stolen.

So how do we circumvent this problem and “hide our key”?

There’s a few different ways we can do this, but in this post, we’ll be exploring the environmental variable file (or .env, for short).

What are environment variables?

Before diving into what this file is, I want to briefly hit on what an environment variable is.

Each time when you run a python script, a terminal is opened and the code is executed. Before the script runs, the terminal session can be configured with environment variables, which you can define in this file.

These variables can be updated or modified to influence the program’s execution environment.

Think of environment variables as a setting on your phone - it’s very similar to how you set your phone to silent mode or enable WiFi. Each setting on your phone dictates how it behaves in different situations.

What is an environment file (.env file)?

An .env file is simply a file that is used in projects to store configuration settings, environment variables, and sensitive information securely.

We want to avoid putting API keys in a Python script:

my_key = "mumbojumbo"

Instead, create a .env file and place your key into it and remember to source it (. /full/path/to/.env) to have the changes take effect. For example:

# Sample .env file
SECRET_KEY=your-secret-key-goes-here
DEBUG=True
API_KEY=your-api-key-goes-here
ANOTHER_API_SECRET=another-api-secret-goes-here

Reading the .env file with Python

To read this file using Python, you’ll need to have the python-dotenv package installed:

pip install python-dotenv

From here, you need to load it into your shell environment and use the os library to retrieve the variable:

import os
from dotenv import load_dotenv

load_dotenv() # loads .env into shell

my_key = os.environ.get('MY_KEY', None) # retrieve it

» Tidbit: the period in front of the file name states that it is a “hidden” file. Most file explorers will not show files that start with the period.

» Pro tip: use .get() when indexing the os.environ dictionary and set the default to None. This prevents a KeyError from happening.

📧Join the Python Snacks Newsletter!🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.