How to set environment variables in Python?

Photo of author

When configuring your Python program, environment variables are an excellent way to do it without updating the source code. Environment variables frequently supplies third-party API keys, network ports, database servers, and any other unique choices, which your application may require to function properly.

Environment variables in Python

This article will discuss several tools and approaches to set environment variables in Python.

How To Use Python To Retrieve Environment Variables

Given below are some of the ways you can use Python to retrieve environment variables:

Using The Dictionary In os.environ

The os.environ dictionary contains all the environment variables in Python. The standard dictionary syntax is the most straightforward approach to getting a variable from within your program.

Using the dictionary in os.environ

When using this approach, Python will throw a KeyError exception if you attempt to import an environment variable that doesn’t exist.

Using the dictionary in os.environ

Utilizing os.environ.get ()

Getting the critical error is a good idea for environment variables that your application needs, but there are some circumstances in which you might wish to make some variables optional. Use the dictionary’s get() function, which returns None if the requested key does not already exist in the dictionary, to prevent the error:

Utilizing os.environ.get ()

Including A Default Value To Use In The Absence Of A Declared Variable

As a second parameter, you may specify a default value for the absent variable that is not None:

Including a default value to use in the absence of a declared variable

Using The os.getenv() Method

The os.getenv() method also allows access to environment variables in Python. The os.environ.get() method and this function both operate in very similar ways. How to use it to access a variable is as follows:

Using the os.getenv() method

When a variable is absent, this function returns None, much like os.environ.get, without raising an exception (). Additionally, it takes a second parameter with a personalized default value:

Using the os.getenv() method

Is os.getenv() a superior option to os.environ? That is up to you. I like to use the os.environ dictionary since it allows me to terminate the application with a KeyError if a necessary variable is not present.

See Also: Why Use Python For Web Development

The Best Way To Set Environment Variables In Python

This section will briefly cover the process of setting environment variables in a terminal or command-prompt window. Dominik Kundel, a coworker of mine, has produced an in-depth blog article titled “How to Set Environment Variables” if you want to know every conceivable technique to set environment variables in Python.

MacOS and Unix

When using a bash or zsh terminal session, there are two main approaches to setting an environment variable. Use of the export keyword is one.

MacOS and Unix

Any scripts or programs you launch from this terminal session will inherit a variable configured in this manner. Remember that environment variables are not preserved anywhere other than inside the shell session’s context; thus, they will vanish once the terminal session is closed.

MacOS and Unix

Since the variable is only set in the environment space of the intended application, the second version has this advantage.

The Microsoft Windows

There are a few choices available if you’re running Windows. See the article at the top of this page if you want to control environmental variables via the control panel.

You can modify an environment variable using the set command while in a command prompt window.

It is also possible to define an environment variable by setting it on the line where the target program is run:

Microsoft Windows

The Microsoft Windows will keep the variable only for the duration of the current session, just like in the Unix example.

The syntax for establishing environment variables is entirely different if you’re using the more recent PowerShell console:

Microsoft Windows

Finally, if you’re using a Unix compatibilities layer like WSL or Cygwin, you must use one of the techniques for bash or zsh specified in the Unix section above.

Utilizing.env files

Are you perplexed by the many methods for setting environment variables? Each platform or shell requiring a distinct process is annoying to me personally.

A .env (pronounced dot env) file is a superior approach to maintaining your environment variables. A text file with each variable defined on a separate line is called an “env file”. With .env files, dealing with environment variables is consistent across all platforms since the format of a .env file is the same on all operating systems. And if that weren’t enough, you can avoid manually configuring your environment variables each time a new shell launches by writing them in a file that Python will automatically import.

Here’s a brief .env file illustration with two variables:

Utilizing.env files

To keep all the variables required by each project organized, create a .env file in the root directory of each project.

Python program will import variables specified in an a.env file into the environment, using the python-dotenv module. To install Python-dotenv in your virtual environment, you can use Pip:

Utilizing.env files

See the instructions for importing an.env file into a Python program below:

Utilizing.env files

Load dotenv() method adds all variable definitions in a file called .env, located in the current directory, to the os.environ dictionary. If the a.env file cannot be located in the current directory, then look for it in the parent directory. A.env file must be located, or the top-level directory must be for the search to stop.

You may explicitly specify the path to your file as an input to load dotenv() to stop python-dotenv from looking through your folders for the a.env file:

Utilizing.env files

When using the load dotenv() method, you have a few more parameters at your disposal. Consult the documentation if you want to learn more about them.

You can access environment variables by utilizing any of the techniques mentioned above after importing the.env file.

Security Information Regarding .env Files

The environment variables you add to your .env files frequently include sensitive data, such as API keys or passwords. Because of this, you should avoid adding these files to the source control repository for your project.

To prevent these files from being accidentally added to source control, it is customary to include an exception for files with this name. You can add a line containing the file’s name to the .gitignore file at the repository’s root for git.

But how can you inform project users which variables to set if you cannot commit the .env file? For this, you may add an example .env file to your repository with a name like “env.example,” which provides the list of variables the project needs but doesn’t include their values. Without revealing sensitive information, this acts as advice for project users.


This post helped you better understand how to configure your Python applications using environment variables.

See Also: Complete Full-Stack Development Roadmap For 2023


Leave a Comment