OS Environment Variables and why the .env file is Python’s best friend 🐍

By | March 27, 2022

The Scenario

I am currently doing the 100 Days of Code challenge using Angela Yu’s Udemy course. In the morning before work starts I do a little bit of it on my MS Windows desktop:

“the setup”

In the evening I’ll commit my changes to my GitHub repository & step away from the desk. After dinner and shenanigans I’ll continue to do the project using my MacBook. I pull for the days changes (on the windows box) and pick up where I left off.

The Problem

Because I’m committing to a public repository:

  • I don’t want to embed any usernames, passwords, API keys, or other types of user IDs into the code I’m committing. There are bots constantly crawling public repos looking for this kind of info to exploit.
  • I also don’t want to use local OS specific environment variables because I’m switching operating systems at least once a day.

The Solution: .env files!

A .env file is a text file in which the variables are defined, one per line. The format the file is exactly the same under both OSes so my workflow is the same.

The process is as follows:

Make sure you have .env in your .gitignore – if you don’t do this your .env file will get committed along with the rest of your files:

my .gitignore for the 100 Days Projects

Install the python-dotenv package into your project:

pip install python-dotenv

Now you can (1) import dotenv (2) use load_dotenv on your target file (3) grab variables from the file when you need them!

Day 35 Weather SMS project

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.