How to work with environmental variables in Uzar

by SkillAiNest

Environmental variables allow you to create applications directly in your source code without tighten information.

They are especially useful for storing API keys, database credentials, and setting settings that change between development, staging and production environment.

In this tutorial, you will learn how to work with environmental variables.

🔗 🔗 Here is a code on the gut hub.

The table of content

Why use environmental variables?

Before diving into the code, let’s understand why the environment varies.

When you do a hard code of the database password or the API key in your own script, you are at risk of exposing sensitive information if your code is combined or is committed to controlling the version.

Environmental variables resolve it by storing the order out of their code base, and making your application more secure and portable in a different environment.

Provisions

Before starting this tutorial, you should be:

  • Azigar is installed on your system, preferably a recent version of Ajgar 3.11 or after

  • Working with basic acquaintance and dictionaries with the syntax

  • A Text Editor or IDE for writing azar code

How to read the environment variable os.environ

Built -in of Azigar os The module provides the basic interface for working with the environmental variable. os.environ Objects act like a dictionary containing the environmental variables available in your process.

This code shows two points for environmental variable reading:

import os


api_key = os.environ('API_KEY')


database_host = os.environ.get('DATABASE_HOST', 'localhost')
database_port = os.environ.get('DATABASE_PORT', '5432')

print(f"Connecting to {database_host}:{database_port}")

In the first point of view, os.environ('API_KEY') Will pick up a KeyError If the variable is not present, which can crash your program.

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/tmp/ipython-input-2466845533.py in ()
      2 
      3 # Get an environment variable (raises KeyError if not found)
----> 4 api_key = os.environ('API_KEY')
      5 
      6 # Safer approach: get with a default value

/usr/lib/python3.12/os.py in __getitem__(self, key)

KeyError: 'API_KEY'

Uses a secure approach os.environ.get()Who looted None Or when the variable disappears, a certain default value. This makes you overcome how the order is handled.

Understand the kind of change

One of the important things to remember is that environmental variables are always safe as strings. When you recover some value '5432' For the port number, this is a wire, not numerical. This means that you will need to convert environmental variables into a suitable type for your application.

For example, if you need to use a database port in the numerical operation, you will need to change it:

database_port = int(os.environ.get('DATABASE_PORT', '5432'))
max_connections = int(os.environ.get('MAX_CONNECTIONS', '10'))

total_capacity = database_port + max_connections  

Bolin values ​​of LOYLL, you will need to check against the representation of the wire:

debug_mode = os.environ.get('DEBUG', 'False').lower() in ('true', '1', 'yes')

Without the appropriate type of conversion, you can run into unexpected behavior or mistakes when your code expects a number but receives the wire.

How to compose environmental variables

You can configure environmental variables within your own script according to the program.

âš  Just keep in mind that these changes only affect the current process and the process of its children.

This code shows how to create, access and remove environmental variables during the run time:

import os


os.environ('APP_ENV') = 'development'
os.environ('MAX_CONNECTIONS') = '100'


print(f"Environment: {os.environ('APP_ENV')}")


if 'TEMP_VAR' in os.environ:
    del os.environ('TEMP_VAR')

The key is to remember that these changes are temporary and only for your life of the process. When your script is over, these modifications end.

Method to create a configuration class to manage environmental variables

In practice, you can manage the environmental variables by creating a configuration class that maintains access to environmental variables and provides verification. This approach makes it easy to update and maintain your configuration information.

Here is a sample configuration class that pushes environmental variable handling in one place.

import os

class AppConfig:
    """Application configuration loaded from environment variables"""

    def __init__(self):
        
        self.api_key = self._get_required('API_KEY')
        self.database_url = self._get_required('DATABASE_URL')

        
        self.debug = self._get_bool('DEBUG', False)
        self.port = self._get_int('PORT', 8000)
        self.log_level = os.environ.get('LOG_LEVEL', 'INFO')
        self.max_workers = self._get_int('MAX_WORKERS', 4)

    def _get_required(self, key):
        """Get a required environment variable or raise an error"""
        value = os.environ.get(key)
        if value is None:
            raise ValueError(f"Required environment variable '{key}' is not set")
        return value

    def _get_bool(self, key, default):
        """Convert environment variable to boolean"""
        value = os.environ.get(key)
        if value is None:
            return default
        return value.lower() in ('true', '1', 'yes', 'on')

    def _get_int(self, key, default):
        """Convert environment variable to integer"""
        value = os.environ.get(key)
        if value is None:
            return default
        try:
            return int(value)
        except ValueError:
            raise ValueError(f"Environment variable '{key}' must be an integer, got '{value}'")

    def __repr__(self):
        """Safe string representation (masks sensitive data)"""
        return (f"AppConfig(debug={self.debug}, port={self.port}, "
                f"log_level={self.log_level}, api_key={'*' * 8})")

Helper _getrequired()For, for, for,. _getbool()And _getint() Handle the type change and verification, making your code further strengthened. __repr__() The method provides a safe method to print without exposing sensitive values ​​such as API keys.

Ensure the desired environmental variables:


os.environ('API_KEY') = 'your_api_key_here' 
os.environ('DATABASE_URL') = 'your_database_url_here' 

Now you can quickly make AN AppConfig Object and use this way:

config = AppConfig()
print(config)
print(f"Running on port {config.port}")

This should give you the sample output like:

AppConfig(debug=False, port=8000, log_level=INFO, api_key=********)
Running on port 8000

Conclusion

I hope you will be helpful this article! Environmental variables provide you with an easy, secure way of creating applications that work permanently in different environments, keeping sensitive information away from your source code.

When working with environmental variables, keep in mind the following:

  • Never commit a secret to control the version. Always add .env You .gitignore Provide the file A .env.example File with dummy values ​​to show other developers that require changes.

  • Failing to lose the desired order. If your application cannot run without any variables of the environment, check them on the startup and make clear errors instead of failing later.

  • Use type conversion as needed. Environmental variables are always wire, so turn them into the appropriate type and handle the conversion mistakes beautifully.

  • Provide sensible defaults. Defulay, defaults such as port numbers or feature flags, make your application easier to run during development.

In addition to the above, try to document your environmental variables. Maintain a list of environmental variables that are in use your application, what they control, and what is needed.

In my next article, you will learn how to raise configuration files. Until then, Happy Coding!

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro