Python
Environment Variables
Python Programming
Coding Tips
Python Development

How to set environment variables in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Environment variables are essential in programming as they store key-value pairs that can affect the way applications behave on a computer. In Python, managing environment variables can be crucial for setting up configurations like API keys, database settings, and other sensitive information that should not be hard-coded into your scripts. This article will guide you through various methods to set and access environment variables in Python.

Understanding Environment Variables

Environment variables are dynamic values that affect the processes or programs on a computer. They can store data such as user preferences, system paths, or configuration settings. In Python, the os module provides functionality to interact with the operating system, including managing environment variables.

Setting Environment Variables

1. Using the Command Line

Before running a Python script, you can set an environment variable directly from the command line:

Unix/Linux/OS X:

bash
export MY_VARIABLE='Some Value'

Windows:

bash
set MY_VARIABLE=Some Value

This environment variable can then be accessed by your Python script.

2. Using Python's os Module

You can also set environment variables directly from within a Python script using the os module:

python
import os

os.environ['MY_VARIABLE'] = 'Some Value'

This sets an environment variable MY_VARIABLE with the value 'Some Value'.

3. Using dotenv Files

For development, using a .env file is a common practice. You can use the python-dotenv package to read and set environment variables from a .env file:

  1. Create a .env file:
 
   MY_VARIABLE=Some Value
  1. Install the dotenv package:
bash
   pip install python-dotenv
  1. Load variables in your script:
python
1   from dotenv import load_dotenv
2   import os
3
4   load_dotenv()
5
6   # Now you can access the environment variable
7   value = os.getenv('MY_VARIABLE')
8   print(value)

4. Using Environment Configuration Files

For more complex configurations, consider using configuration files in formats like YAML, JSON, or INI, along with packages like PyYAML, json, or configparser.

Accessing Environment Variables

To access environment variables within a Python script, you can use the os module as follows:

python
1import os
2
3value = os.getenv('MY_VARIABLE')
4if value:
5    print(f"MY_VARIABLE: {value}")
6else:
7    print("MY_VARIABLE is not set.")

The os.getenv() function is preferred because it allows you to specify a default value if the environment variable is not found:

python
value = os.getenv('MY_VARIABLE', 'Default Value')

Common Practices

  • Security: Never hard-code sensitive information like passwords or API keys directly in your source code. Utilize environment variables or external files.
  • Version Control: Do not commit .env files to version control. Consider using a .env.example file to list necessary variables without revealing sensitive data.
  • Portability: Using environment variables makes your applications more portable and easier to configure across different environments (development, testing, production).

Summary Table

MethodDescriptionProsCons
Command LineSet variables before running Python scriptDirect and straightforwardTemporary and session-specific
Python os ModuleSet within the Python scriptDynamic and script-containedNot persistent across sessions
.env Files + python-dotenvLoad variables from .env fileEasy management and automationRequires an additional library
Configuration FilesUse structured files like YAML, JSON, or INIHighly structured and flexibleMore complex setup

Conclusion

Environment variables are a powerful tool for managing application configurations in a secure and efficient way. By understanding various methods of setting and accessing these variables, you can ensure that your Python applications are more secure, maintainable, and adaptable to different environments. Whether you choose command line methods, utilize the os module, or manage configurations through dotenv or structured files, each approach offers distinct advantages suited to different use cases.


Course illustration
Course illustration

All Rights Reserved.