
🔐 Hardcoding API keys in your Python code? That’s a security mistake. Here’s the right solution.
Storing passwords and tokens in source code is dangerous: if it’s uploaded to Git, it’s exposed. 7 practical techniques to do it right:
📄 Local .env file — store secrets in
KEY=value, never in version control. Load withpython-dotenv.📋 .env.example — a valueless version you DO commit to document what keys are needed.
🌍 System environment variables — for production:
os.environ['API_KEY']instead of hardcoding.🏗️ Separate settings from code — a
settings.pymodule centralizes loading and validation of secrets.☁️ Secret managers — AWS Secrets Manager, GCP Secret Manager, Vault for enterprise environments.
✅ Validate at startup — verify all keys are present before the app starts.
🚫 pre-commit hooks — automatically detect if someone tries to commit a secret.
💡 Explanation in a nutshell#
A secret in your code is like leaving a house key under the doormat: anyone who sees the code (collaborators, public repositories, logs) can use it. The solution is to store secrets outside the code, in a .env file that’s never uploaded to Git, and load them into your program when needed.
More information at the link 👇

