How do I use environment variables in Python?
I'm working on a little personal Python project and I'd like to store my API keys without hardcoding them. How do you normally go about loading environment variables? I'm using VS Code on Windows.
I'm working on a little personal Python project and I'd like to store my API keys without hardcoding them. How do you normally go about loading environment variables? I'm using VS Code on Windows.
The simplest way is to use the `os` module with `os.environ.get('YOUR_KEY')` to retrieve your variables. You can also install `python-dotenv` and create a `.env` file at the root of your project (with `API_KEY=your_key_here`), then do `from dotenv import load_dotenv` and `load_dotenv()` on startup - it's cleaner and you just need to add `.env` to your `.gitignore` so you don't commit it. On Windows with VS Code, it works exactly the same as anywhere else, you just gotta be careful to restart the terminal after modifying `.env` or the changes won't always load.
Pretty good answer above 👍 Just one more thing: if you're using `python-dotenv`, don't forget to add `.env` to your `.gitignore` or you'll accidentally push your API keys to GitHub and that's not great 😅
Log into answer.