Environmental Variables in Python
Tags: python, env, environmental, decouple
Published: 2020-07-19 16:34:22

# Environmental Variables in Python

Before we begin let's look at our little vocabulary

    ENV = Environmental Variable

    ENVs = Environmental Variables

Haven't really built any major project with Python except writing scripts or solving simple Algorithms. Today I was making changes to my [Facebook_autopost_bot](https://github.com/igmrrf/Facebook_autopost_post) when I realized am gonna need to set this up to enable others use the code and also share it openly on Github without letting out my passwords and configurations.

Maybe you're already using **ENVs** in your Python scripts or applications, but if your haven't started then now is a good time to consider a change. I believe prior to you readint his, you already know what an ENV is so no need to make this post longer.
NOTE: ENVs exist outside of your code as part of your server environment— can help you by both streamlining and making more secure the process of running your scripts and applications. Automation and Security are the major reasons for adopting ENVs

## Let's Start

In Python environment variables are implemented using the _os_ package.

Sample Code:

    import os

    print(environ)

Result: Will show you all the ENVs existing on your machine(object containing a lot of information about your machine, os, services etc.)

Note: This is an edited (shortened) output for the purpose of the blog post length.

    >>> environ({'SHELL': '/bin/bash', 'LSCOLORS': 'ExFxBxDxCxegedabagacad', 'SESSION_MANAGER': 'local/igmrrf:@/tmp/.ICE-unix/2554,unix/igmrrf:/tmp/.ICE-unix/2554', 'QT_ACCESSIBILITY': '1', 'APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL': 'true', 'LANGUAGE': 'en_NG:en', 'QT4_IM_MODULE': 'ibus', 'GNOME_SHELL_SESSION_MODE': 'ubuntu', 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh', 'XMODIFIERS': '@im=ibus', 'DESKTOP_SESSION': 'ubuntu', 'SSH_AGENT_PID': '2467', 'NO_AT_BRIDGE': '1', 'GTK_MODULES': 'gail:atk-bridge', 'DBUS_STARTER_BUS_TYPE': 'session', 'PWD': '/home/igmrrf/Desktop/Writings/ENVs in Python',   'TERM_PROGRAM': 'vscode', '_': '/usr/bin/python3'})

### COMMANDS for Reading and Writing environment variables:

### READING

    os.environ.get('USER')
    os.environ['User']
    os.getenv('USER')

    >>> igmrrf
    >>> igmrrf
    >>> igmrrf

The commands will print out your current username

Note: If there no environment variable matching the key, it'll return _None_

### WRITING

To change an ENV

```shell
os.environ['USER'] = 'tldo'
```

    os.environ['USER']

    >>>tldo

### To Clear an ENV

```shell
os.environ.pop('USER')
```

When trying to access that ENV, you'll get _None_

```shell
os.environ.get('USER')

>>> None
```

### To Clear All ENV

```shell
os.environ.clear()
```

When trying to access any ENV, you'll get _KeyError_

```shell
os.environ.get('USER')

>>> KeyError: key does not exist.
```

NOTE: I was scared at first about this clear function but don't worry, the settings you apply in your python projects and scripts don't affect other projects outside that specific process or affect machine wide ENVs.If you wish to affect a machine wide change on your machine you'll need to run these commands from _bash_ with _sudo_ priviledges

## Using ENVs

In order to use these variables as we keep on building scripts and as programmers and developers, effeciency, speed and optimization is a major criteria, we need to assign the function of handling these variables to an external file.

A package that does this effortlessly is _python-decouple_

Open your terminal & Run

    pip install python-decouple

if your use Linux ubuntu and install python using _sudo apt install python3_ then run

    pip3 install python-decouple

A useful package for handling ENVs locally instead of us acccessing our os(_import os_) and manipulating which is a bit complex :wink:

If you've already got it installed, you'll get

    Requirement already satisfied: python-decouple in /home/your_name/.local/lib/python3.8/site-packages (3.3)

else it will be installed in few seconds

## Using Python-decouple

### Let's get started by creating and opening our .env file at the root of your project

```shell
$ touch .env
$ code .env
```

Note: _code_ is a command that comes with [VsCode](www.visualstudiocode.com). Only run it if you have VsCode install and configured correctly on your machine

Then configure the file as follows

```
username=igmrrf
PASSWORD=12345
URL=https://api.igmrrf.com
```

Then import Python-decouple in Your Python script where you need these variables

```
from decouple import config

print(config('URL'))
print(config('USERNAME'))

>>> your_api_endpoint
>>> igmrrf
```

Wasn't that easy? :smile:

Python provides a package for almost everything, that's one of the reasons Python is so popular and getting more recognition.

If you've got a second, either tweet about this or go check out a python package :wink: