Skip to main content

An environment variable parser library with type hint and conversion support.

Project description

PyPI - Python Version PyPI - Version PyPI - Types

GitHub License

Mypy Ruff uv

test codecov

enve

An environment variable parser library with type hint and conversion support.

The complete documentation is available here.

Installation

Install enve (preferably in a virtual environment) with:

pip install enve

Usage

Python

enve.get is the main package function. It's essentially os.getenv on (arguably unnecessarily strong) steroids. It's advantage is that it will automatically validate the environment variable's data type based on what you desire and provide typing support for the used variable. For complete details, see the enve.get function docstring.

The example below illustrates how you can obtain environment variables and convert them to a desired data type.

import enve


ENVVAR = enve.get("ENVVAR")  # will be parsed and typed as `str`
ENVVAR_STR = enve.get("ENVVAR", dtype=str)  # will be parsed and typed as `str`
MY_SWITCH = enve.get("MY_SWITCH", dtype=bool)  # will be parsed and typed as `bool`
HASH_SALT = enve.get("HASH_SALT", dtype=bytes)  # will be parsed and typed as `bytes`
RANDOM_SEED = enve.get("RANDOM_SEED", dtype=int)  # will be parsed and typed as `int`
MY_PI = enve.get("MY_PI", dtype=float)  # will be parsed and typed as `float`
CUDA_VISIBLE_DEVICES = enve.get("CUDA_VISIBLE_DEVICES", dtype=list)  # will be parsed and typed as `list`
CUDA_VISIBLE_DEVICES = enve.get("CUDA_VISIBLE_DEVICES", dtype=tuple)  # will be parsed and typed as `tuple`

Supported data types are bool, bytes, float, int, str (the default), list and tuple.

In all these examples, a ValueError will be raised if the environment variable is not defined. To use a default value, set the default parameter accordingly. Note that the default value's type must be None or the same as the expected return type.

import enve


ENVVAR_WITH_DEFAULT = enve.get("MISSING_ENVVAR", default="foobar")

enve.get also supports Docker secrets. By setting the docker_secret parameter to True or to the name of a Docker secret, enve.get will attempt to retrieve its value (even if unset in the current environment).

import enve


# The following snippet will:
# 1. Check whether the `MY_SECRET` envvar exists. If true, this will be returned.
# 2. Check whether `/run/secrets/MY_SECRET` exists. If true, the file will be read
#    and the value will be returned.
# 3. Check whether `/run/secrets/my_secret` exists. If true, the file will be read
#    and the value will be returned.
# 4. Raise a `ValueError` as no default is provided.
MY_SECRET = enve.get("MY_SECRET", docker_secret=True)

On Windows, the C:\ProgramData\Docker\secrets directory is used to search for Docker secrets.

Improved error messages

Rather than obtaining a sometimes annoyingly obscure error when accessing an environment variable, enve.get provides an arguably nicer error message.

Using os.environ on a missing environment variable:

>>> import os
>>> os.environ["FOOBAR"]
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    os.environ["FOOBAR"]
    ~~~~~~~~~~^^^^^^^^^^
  File "<frozen os>", line 716, in __getitem__
KeyError: 'FOOBAR'

Using enve.get:

>>> import enve
>>> enve.get("FOOBAR")
Traceback (most recent call last):
  File "<python-input-6>", line 1, in <module>
    enve.get("FOOBAR")
    ~~~~~~~~^^^^^^^^^^
  File "enve/parser.py", line 638, in get
    raise EnvError(err_msg)
enve.parser.EnvError: Environment variable 'FOOBAR' is not set and no default or default_factory is provided.

Note that enve.EnvError exceptions inherit from ValueError and KeyError so they can be caught the same way as if you were using os.environ.

CLI

Once pip-installed, the enve CLI command will be available for usage. This can be used to echo environment variable values without worrying about variable substitution (e.g., $FOOBAR vs. ${FOOBAR} vs. %FOOBAR% vs. $Env:FOOBAR).

Some common usage examples are:

$ FOOBAR=1 enve FOOBAR
1

# This will output an empty string.
$ enve UNSET_VAR -d


$ enve UNSET_VAR -d default
default

# Also check if the var is a docker secret.
$ enve UNSET_VAR -s

# Print all variables in the current environment
$ enve

All enve command options are listed below:

usage: enve [-h] [-d [DEFAULT]] [-s [DOCKER_SECRET]] [-0] [-j] [--version] [env_var]

Print environment variables values without worrying about substitutions.

Positional arguments:
  env_var               The environment variable to print the value of. If unset, print all environment variables.

Optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit

Parser options:
  -d, --default [DEFAULT]
                        The default value to use if the environment variable is not set. This can be used a boolean flag
                        (i.e., this option can be set without a value). In this case, the default value will be an empty
                        string if the environment variable is not set.
  -s, --docker-secret [DOCKER_SECRET]
                        If set, specify that the environment variable can also be a Docker secret. This can be used a boolean
                        flag (i.e., this option can be set without a value). If set this way, a docker secret with the same
                        name as the environment will be search for. If set with a value, the value will be used as the docker
                        secret name.

Global environment options:
  -0, --null            End each output line with a null character instead of a newline when printing all environment
                        variables.
  -j, --json            Output the environment variable as a JSON object. This is only used when printing all environment
                        variables.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

enve-0.2.1.tar.gz (85.8 kB view details)

Uploaded Source

File details

Details for the file enve-0.2.1.tar.gz.

File metadata

  • Download URL: enve-0.2.1.tar.gz
  • Upload date:
  • Size: 85.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for enve-0.2.1.tar.gz
Algorithm Hash digest
SHA256 e1c9f8f0ceef09d9ebd37b9dda519e66e5fb5bece02e5a61fce97bbe9deafd4d
MD5 bc04f39ae52009971e3e863808a0b678
BLAKE2b-256 0a6fc5726507d80ca4c33fd4d6fb5dd449fb6a0cf0d6611f954a6aead566dece

See more details on using hashes here.

Provenance

The following attestation bundles were made for enve-0.2.1.tar.gz:

Publisher: release.yaml on aachick/enve

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page