Explain Codes LogoExplain Codes Logo

How can I access environment variables in Python?

python
environment-variables
os-module
best-practices
Anton ShumikhinbyAnton Shumikhin·Sep 24, 2024
TLDR

If you're in a hurry, here's the quick-and-dirty, no-frills guide:

import os my_var = os.getenv('MY_VARIABLE') # "Abra-ca-dabra!" print(my_var if my_var else 'Oops, your spell failed. No such environment variable.') # Hogwarts would be disappointed!

Note: This approach retrieves an environment variable's value for immediate use or checks, safely returning None if the sought VAR_NAME doesn't exist. Fast, simple, and avoids any face-palming KeyError moments!

Phases of environment variables

Understanding environment variables is a game of four steps:

  1. Retrieving an environment variable: os.getenv('VAR_NAME', default_value)
  2. Checking if a variable exists: 'VAR_NAME' in os.environ
  3. Setting a new environment variable: os.environ['NEW_VAR_NAME'] = 'value'
  4. Modifying an existing environment variable: os.environ['VAR_NAME'] = 'new_value'

And if you're just plain curious about all the variables you have:

  1. Accessing all the environment variables: print(dict(os.environ))

But remember, no peeking at os.environ['VAR_NAME'] without doing your existence check homework first. Otherwise, you're in for an unexpected KeyError pop-quiz!

Mastering the "Undefined" Art

Sometimes, you may try to get a tool that's just not there. Fear not, try-except is your friend!

import os try: oh_so_important_thingie = os.environ['VERY_IMPORTANT_TOOL'] except KeyError: print('I swear it was here last time! Set the VERY_IMPORTANT_TOOL, please.') # Oh dear, no tool? Maybe it's time to quit? (only if it's crucial of course!) import sys sys.exit(1) # "I'm outta here!"

This way, you provide a safety net for your code while giving the user a gentle nudge about setting up their toolbox properly.

Overseeing your toolbox

To have a heart-to-heart with all the environment variables, take a stroll through them with a loop:

for key, value in os.environ.items(): print(f'{key}: {value}') # "#ChattyPython"

And if you're feeling a bit controlling:

  • To arrange your toolbox's layout (setting paths): os.environ['PYTHONPATH'] = '/path/to/dir' or os.environ['PYTHONHOME'] = '/path/to/python/home'
  • To see your meticulously organized paths: os.environ.get('PYTHONPATH') or os.environ.get('PYTHONHOME')

And remember, when dealing with secret plans and sensitive blueprints (secrets and configurations), always access via environment variables as if your code's life depends on it!

Keeping a secret? No problem!

Have sensitive info to keep under wraps? Like your secret cookie recipe? (Or, um, passwords, and API keys). Make sure you fetch them securely via environment variables:

import os my_big_secret = os.environ.get('SECRET', default='Not telling!')

Keep your secrets safe and secure, out of prying eyes, and ensure your script's reputation stays squeaky clean!