We earn commission when you buy through affiliate links.
This does not influence our reviews or recommendations.Learn more.
Want to manage your config better?
Learn how to work withenvironment variables in Python.
When I was teaching myself Python, Id build projects to apply what Id just learned.
A subset of those involved connecting to a database and querying it using Python.
Which meant I needed to store the database configuration and sensitive info such as username and password for authentication.
Hard coding such sensitive info in a Python script was not a good idea.
I learned how to use config files and environment variablesalong with Pythons built-in modules to work with them.
In this tutorial, Ill walk you through environment variables and how to work with them in Python.
What Are Environment Variables?
Environment variables are variables external to your system that store configuration information, system prefs, and the like.
They are typically managed by the operating system or the program environment.
Andos.environis adictionary of environment variables.
Thenames of the environment variablesandtheir valuesare the keys and values of the dictionary, respectively.
Instead of aKeyError, theget()method returnsNoneif the variable is not found.
Then let it pass silently or be subsumed in theNonethat theget()method returns.
If the environment variables are not set, we provide default values to use.
Example 2:Managing API Keys
Lets take another example that involves the use of API keys.
When you sign up for an OpenAI account, youd (typically see) some free time-limited API credits.
Grab your API key by navigating toSettings > View API Keys.
Which is helpful when you want to run system programs in Python.
In the following example, we modify thePATHenvironment variable by tapping into theos.environdictionary.
Installing python-dotenv
To usepython-dotenv, you should probably install it first.
This is also a valid (and less commonly used) way to access environment variables.
Heres the output:
In this example:
Conclusion
And thats a wrap!
I hope youve learned how to manage configuration and sensitive information using environment variables in Python applications.
For managing secrets, I recommend exploring tools like HashiCorp Vault or AWS Secrets Manager.
Next, you may also read about Python Floats and Python Flask.