How to set environment variables in Python?

745    Asked by rethaw_6014 in Python , Asked on Aug 6, 2025

Setting environment variables in Python is useful when you want to manage sensitive data like API keys or configuration settings outside your main codebase. But how exactly do you define or access these variables within a Python script? Let’s find out.

Answered by KimberlyStein

Setting environment variables in Python is a common practice when you want to keep your code clean and secure — especially when dealing with credentials, API keys, or configuration data that shouldn’t be hard-coded into your script.

 How to set environment variables in Python

Python provides the os module to work with environment variables. You can both read and set environment variables using this module.

 Setting an environment variable:

You can set an environment variable within a Python script like this:

import os
os.environ["MY_VARIABLE"] = "my_value"

However, this variable will only persist for the duration of the script execution.

 Reading an environment variable:

To retrieve the value of an environment variable:

value = os.getenv("MY_VARIABLE")
print(value)

 Tips & Best Practices:

  • Use environment variables to manage secrets and sensitive information securely.
  • For permanent settings, define them in your system's environment or use a .env file with packages like python-dotenv.

Example using python-dotenv:

from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("API_KEY")

 Note:

  • Environment variables set in the script do not affect the system’s environment variables permanently.
  • Using environment variables in Python is a clean and secure way to configure your applications, especially when deploying to production environments.



Your Answer

Answers (2)

Learn how to patch macOS on old Macs using OpenCore Legacy Patcher and gain access to features only found on newer macOS versions.

11 Months
palabr_2597
Learn how to patch macOS on old Macs using OpenCore Legacy Patcher and gain access to features only found on newer macOS versions.

Clear and practical! Using environment variables keeps sensitive data secure and your codebase clean. `os.environ` is the key to accessing them in Python. 


11 Months

Interviews

Parent Categories