DEV Community


Posted on


Environment Variables in Python

Environment variables are crucial in development so you don't accidentally commit keys/passwords up to a repo. Web developers in JavaScript will process.env to access their environment variables.

The cleanest way I've figured to do this is Python is to utilize an Anaconda environment and setting them there accessing them in code with os.environ.

Here is a quick example from your terminal:

conda create -n test-env
conda activate test-env
conda env config vars set my_var=value
conda activate test-env
Enter fullscreen mode Exit fullscreen mode

Once you have set your variable, you have activate your environment again as above.

To check if it worked, you can either echo my_var to check it specifically or conda env config vars list to see a list of them all.

If you want to reuse an environment, you can use a shell script to set and unset your variables upon deactivation. See docs for how to do it in Windows (with a .bat file) and Mac/Linux.

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git