Make use of environment variables in your Python code for improved security and smoother workflows.
We love Python at Nylas – in fact, we built our suite of email, calendar, and contacts APIs on Python. We’ve learned a few lessons along the way, and gained some new insights into environment variables in Python that we wanted to share.
You may already be using environment variables in your Python scripts and applications, but if not, now is a good time to consider using them. Why, you ask? Environment variables— variables that exist outside of your code as part of your server environment— can help you by both streamlining and making more secure the process of running your scripts and applications.
Automation – environment variables help you move away from manually updating your environment variables each time they change. For example, instead of manually changing the “user” part of a path when you run a script on someone else’s machine, you can use an environment variable that returns the name of that user. This means you no longer have to remember to change that when using a script on a different system.
Improve security practices – one major advantage to using environment variables is when there are aspects of your code you don’t want others to see, such as API tokens that grant access to your accounts. If this token is stored as an environment variable you don’t need to explicitly type it out in the file, you only need to call the environment variable. This also means that other people can use your code without having to hardcode their own API tokens.
This post will teach you everything you need to know to make use of environment variables with Python:
First, assess when it makes sense to use them. Keep in mind that environment variables are inherently not linked with the rest of the code. This means that it’s best to use it in cases where having the variable change with the environment is necessary to keep scripts updated. Common use cases for environment variables include authentication keys (like the API token example we mentioned) and execution mode (e.g. development, staging, production).
Next, let’s take a look at actually implementing these variables. You will eventually bring them into your code, but for now, open up your Python interpreter so we can walk through a few fundamentals together.
How to Get Environment Variables With Python
Environment variables are implemented through the os package, specifically os.environ.
To see all environment variables on your system just call it:
There are a few basic commands for implementing environment variables:
One of the first things you’ll want to know is the current value for specific environment variables in your session. For that, there’s os.environ.get(). This retrieves the value of an environment variable currently set on your system.
If there isn’t an environment variable matching the key, it’ll return None:
How to Set Environment Variables in Python
You can also set environment variables to new strings. This is done in a similar manner to Python dictionaries. It’s important to note that this changes the environment variable in this session. In other words, changing the environment variable here will not affect the environment variable anywhere else.
os.environ['USER'] = 'Bob'
If you need to clear a single environment variable in the session you can use os.environ.pop() with the key and if you need to clear all environment variables you can use os.environ.clear()
It’s important to remember that the settings you apply in a Python script don’t work outside that specific process; os.environ doesn’t overwrite the environment variables system-wide. If you need to permanently delete or set environment variables you will need to do so with a shell environment, such as Bash.
How to Use dotenv Manage Environment Variables
As you increase the number of environment variables you use, you may want to use a library like dotenv to help manage them. It allows you to set or update the environment variables for files in a specific directory by reading them in from another file. This is useful when you delineate different stages of your product by having them in different directories. By using dotenv, you ensure that the environment variables automatically adjust to the environment you have selected by working in that directory. Keep in mind, however, that dotenv is a separate file, and take care not to overlook it when transitioning across systems.
dotenv reads in environment variables from a file named .env. The file should be formatted as follows:
api-token = "abcdef_123456"
Once that’s created and placed in the same folder as your Python file, environment variables can be called like so:
From dotenv import load_dotenv
token = os.environ.get("api-token")
Like many aspects of Python, implementing environment variables isn’t cumbersome, provided you have the right tools. By making use of the os package (especially os.environ), along with dotenv when the situation calls for it, you have all the tools you need to begin using environment variables in Python.