I think storing credentials inside another *py file is your safest bet. Then just import it. Example would look like this

config.py

username = "xy"
password = "abcd"

main.py

import config
login(config.username, config.password)
Answer from kecer on Stack Overflow
Top answer
1 of 5
116

I think storing credentials inside another *py file is your safest bet. Then just import it. Example would look like this

config.py

username = "xy"
password = "abcd"

main.py

import config
login(config.username, config.password)
2 of 5
18

I was dealing exactly the same question and actually ended up with the same solution as kecer suggested. Since I need to use it in dozens of scripts, I've created own library. Let me share this solution with you.

credlib.py -- universal library to handle credentials

class credential:
    def __init__(self, hostname, username, password):
        self.hostname = hostname
        self.username = username
        self.password = password

mycredentials.py -- my local file to store all credentials

from credlib import credential
sys_prod = credential("srv01", "user", "pass")
sys_stg = credential("srv02", "user", "pass")
sys_db = credential("db01", "userdb", "passdb")

mysystemlib.py -- this is a general library to access my system (both new credential system and legacy is supported)

from credlib import credential

def system_login(*args): # this is new function definition
#def system_login(hostname, username, password): # this was previous function definition

    if len(args) == 1 and isinstance(args[0], credential):
        hostname = args[0].hostname
        username = args[0].username
        password = args[0].password
    elif len(args) == 3:
        hostname = args[0]
        username = args[1]
        password = args[2]
    else:
        raise ValueError('Invalid arguments')

    do_login(hostname, username, password) # this is original system login call

main.py -- main script that combines credentials and system libs

from mycredentials import sys_stg, sys_db
import mysystemlib
...
mysystemlib.system_login(sys_stg)

Please note that the legacy hostname/username/password way still works so it does not affect old scripts:

mysystemlib.system_login("srv02", "user", "pass")

This has a lot benefits:

  • same credential system across all our python scripts
  • files with passwords are separated (files can have more strict permissions)
  • files are not stored in our git repositories (excluded via .gitignore) so that our python scripts/libs can be shared with others without exposing credentials (everyone defines their own credentials in their local files)
  • if a password needs to be changed, we do it at a single place only
🌐
GitGuardian
blog.gitguardian.com › how-to-handle-secrets-in-python
Python Secrets Management: Best Practices for Secure Code
December 5, 2025 - TL;DR: - Hardcoding secrets in Python exposes organizations to breaches and compliance risks. - This guide covers secure patterns for managing python secrets: .env/JSON files, environment variables, cloud secret managers, and KMS solutions like HashiCorp Vault.
People also ask

What are the most secure methods for managing secrets in Python applications?
Secure methods include using environment variables, external secrets files excluded from version control, cloud secrets managers such as AWS Secrets Manager, Azure Key Vault, or GCP Secret Manager, and enterprise-grade tools like HashiCorp Vault. Hardcoded secrets must be avoided, and rotation, auditing, and least-privilege access should be enforced.
🌐
blog.gitguardian.com
blog.gitguardian.com › how-to-handle-secrets-in-python
Python Secrets Management: Best Practices for Secure Code
How do cloud secrets managers integrate with Python applications for secure secret retrieval?
Cloud secrets managers provide Python SDKs such as boto3, azure-keyvault-secrets, and google-cloud-secret-manager that authenticate securely and retrieve secrets at runtime, supporting rotation and eliminating static credentials.
🌐
blog.gitguardian.com
blog.gitguardian.com › how-to-handle-secrets-in-python
Python Secrets Management: Best Practices for Secure Code
What advanced security measures should be implemented when managing secrets in Python at scale?
Implement automated rotation, centralized audit logging, encryption at rest, and use secrets.compare_digest() to prevent timing attacks. Consider HSMs or secure enclaves for high-value secrets and ensure secrets are cleared from memory promptly.
🌐
blog.gitguardian.com
blog.gitguardian.com › how-to-handle-secrets-in-python
Python Secrets Management: Best Practices for Secure Code
🌐
Python
docs.python.org › 3 › library › secrets.html
secrets — Generate secure random numbers for managing secrets
Source code: Lib/secrets.py The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, ...
🌐
PyPI
pypi.org › project › python-secrets
python-secrets 24.10.12
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Beagle Security
beaglesecurity.com › blog › article › secrets-in-python.html
How to handle secrets in Python?
November 7, 2023 - You might have a .env file for your local development environment and a env.dev file for your cloud development production environment. To handle such scenarios effectively, consider the following code snippet: from dotenv import dotenv_values secrets = dotenv_values(".env") local_secrets = dotenv_values(".env.dev") def main(): api_key = secrets.get("API_KEY") api_secret = local_secrets.get("SECRET_KEY") print(f"API_KEY: {api_key}") print(f"API_SECRET: {api_secret}") if __name__ == "__main__": main()
🌐
Reddit
reddit.com › r/python › managing secrets like api keys in python - why are so many devs still hardcoding secrets?
r/Python on Reddit: Managing secrets like API keys in Python - Why are so many devs still hardcoding secrets?
March 15, 2023 -

The recent State of Secrets Sprawl report showed that 10 million (yes million) secrets like API keys, credential pairs and security certs were leaked in public GitHub repositories in 2022 and Python was by far the largest contributor to these.

The problem stems mostly from secrets being hardcoded directly into the source code. So this leads to the question, why are so many devs hardcoding secrets? The problem is a little more complicated with git because often a secret is hardcoded and removed without the dev realizing that the secret persists in the git history. But still, this is a big issue in the Python community.

Managing secrets can be really easy thanks to helpful Pypi packages like Python Dotenv which is my favorite for its simplicity and easy ability to manage secrets for multiple different environments like Dev and Prod. I'm curious about what others are using to manage secrets and why?

I thought I'd share some recent tutorials on managing secrets for anyone who may need a refresher on the topic. Please share more resources in the comments.

Managing Secrets in Python - Video

Managing Secrets in Python - Blog

Top answer
1 of 30
161
I think folks often miss configuring gitignore files to avoid accidental commits of files that contain secrets, even when well intentioned. You called it out as important, but it happens frequently enough (for secrets and other data that shouldn't be committed, too)
2 of 30
86
Part of it is that secrets management fits awkwardly into current development approaches. It's quite common for projects nowadays to take an "infrastructure as code" approach. And it's a good approach. Your repo contains everything you need to deploy your code, and it'll do it repeatably in different environments. Except secrets. There are a few decent secret management tools out there, but even with the best of them, secrets have to be managed manually and handled separately in different environments. This breaks repeatability, since a successful deployment to a test environment doesn't tell you your code will successfully deploy to production. I've never come across an approach to secret management that solves this problem. It's also worth considering that when you start a project, you probably don't yet have a secrets management solution in place. The first time you need to add code to your project that needs secrets, you need to put one in place. This is something I'm very strict with on my team (no secrets in code, not even once), but it means you need to stop and set up a secrets management solution, and I can certainly understand how a less strict team lead would choose to just say "it's tech debt, we'll get this ticket implemented and then set it up", or how a junior developer might not think to discuss this with someone.
🌐
Reddit
reddit.com › r/learnpython › how to securely store secrets in python?
r/learnpython on Reddit: How to Securely Store Secrets in Python?
July 17, 2024 -

Hello, I was wondering what's the most secure way to store secrets (API Keys, passwords, tokens, etc) in python. I know in powershell for example there's a built in module for doing so. As far as I know you store your secrets in a config.py file of sorts. But still all anyone has to do is just open that file and your passwords are visible in plain text... What are the recommended options for doing this?

Thanks!

Find elsewhere
🌐
Medium
medium.com › @michael.hannecke › secure-python-secret-management-cloud-local-e80cfa986d4c
How to handle secrets in python | Medium
August 28, 2024 - The easiest way to store and retrieve a secret or a variable in Python is via a local hidden file like “.env” or “.secret”. When using these files always ensure to exclude these files from being added to your source control.
🌐
Medium
medium.com › @kimberly.d.benton › env-how-to-keep-a-secret-python-react-7cdf77848f88
.ENV — How to keep a secret (Python) | by Kimberly Benton | Medium
August 6, 2023 - If you kept it in the app.py file as was shown and committed that information to github, then your secret key is secret no more. You will definitely need to create a new one and this post will show you how to create an .env file for a python file (and react if you need to create something private ...
🌐
GitHub
gist.github.com › radcliff › 47af9f6238c95f6ae239
One way to work with secrets in Python · GitHub
One way to work with secrets in Python · Raw · .gitignore · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
DZone
dzone.com › data engineering › databases › how to handle secrets in python
How To Handle Secrets in Python
March 2, 2023 - The .env file is typically used to store secret keys and passwords. We will use the python-dotenv package for accessing the content of the .env file.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › secrets.py
cpython/Lib/secrets.py at main · python/cpython
managing secrets such as account authentication, tokens, and similar. · See PEP 506 for more information. https://peps.python.org/pep-0506/ · """ · __all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom', 'token_bytes', 'token_hex', 'token_urlsafe', 'compare_digest', ] ·
Author   python
🌐
GitHub
github.com › jsdalton › secrets.py
GitHub - jsdalton/secrets.py: Simplified encryption and decryption of strings and files. · GitHub
Secrets.py is a small Python library that makes it easy to encrypt and decrypt both messages and files.
Author   jsdalton
🌐
GitHub
github.com › anthonynsimon › secrets-vault
GitHub - anthonynsimon/secrets-vault: Simple encrypted secrets for Python
This can be used to separate your secrets by environments such as prod, staging, dev, each having with their own key. You can also configure the filepaths at which your secrets.yml.enc and master.key files are located.
Author   anthonynsimon
🌐
Keeper
docs.keeper.io › en › keeperpam › secrets-manager › developer-sdk-library › python-sdk
Python SDK | KeeperPAM and Secrets Manager | Keeper Documentation
March 14, 2026 - To protect against losing access to your secrets when network access is lost, the Python SDK allows caching of secrets to the local machine in an encrypted file.
🌐
Microsoft Learn
learn.microsoft.com › en-us › azure › key-vault › secrets › quick-create-python
Quickstart – Azure Key Vault Python client library – manage secrets | Microsoft Learn
January 30, 2026 - The Azure Key Vault secret client library for Python allows you to manage secrets. The following code sample demonstrates how to create a client, set a secret, retrieve a secret, and delete a secret. Create a file named kv_secrets.py that contains this code.
🌐
GitHub
github.com › dmnd › secrets.py › blob › master › secrets.py
secrets.py/secrets.py at master · dmnd/secrets.py
#!/usr/bin/env python · · _HELP = """usage: secrets.py <command> · Commands: encrypt: Add new secrets. Overwrites the ciphertext · with a newly encrypted secrets.py · · decrypt: Discard changes to secrets.py. Overwrites · secrets.py by decrypting the ciphertext.
Author   dmnd