Skip to main content

Load and access environment variables with type casting

Project description

cdotenv

A Python library for loading and accessing environment variables from .env files or StringIO with type casting. Licensed under GPL 3.

Installation

pip install cdotenv

Usage

Loading Environment Variables

The load function loads environment variables into os.environ from a .env file, a custom file path, or a StringIO object.

  • Default .env file:

    from cdotenv import load
    load()  # Loads from .env in current directory
    
  • Custom file path:

    from cdotenv import load
    from pathlib import Path
    load(Path("custom.env"))
    
  • StringIO:

    from cdotenv import load
    from io import StringIO
    load(StringIO("KEY=VALUE\n"))
    

The .env file should contain KEY=VALUE pairs, with comments (#) and empty lines ignored:

# Comment
KEY1=VALUE1
KEY2=VALUE2

Accessing Environment Variables with Type Casting

The Environ class allows type-hinted access to environment variables with automatic type conversion.

from cdotenv import Environ

class MyEnviron(Environ):
    DEBUG: bool
    DATABASE_URL: str
    TIMEOUT: int
    SEED: float

env = MyEnviron()
print(env.DEBUG)  # True if os.environ["DEBUG"] = "true"
print(env.DATABASE_URL)  # str, e.g., "postgresql://user:pass@localhost/db"
print(env.TIMEOUT)  # int, e.g., 30
print(env.SEED)  # float, e.g., 42.5
  • Raises ValueError if a variable is missing or cannot be converted to the specified type.
  • Raises AttributeError for undefined attributes.

Custom Type Conversion

Use the field decorator for custom conversion logic:

from cdotenv import Environ, field

class MyEnviron(Environ):
    LIST: list = field(lambda x: x.split(","))

env = MyEnviron()
print(env.LIST)  # ["a", "b", "c"] if os.environ["LIST"] = "a,b,c"
  • Raises ValueError if the converted value does not match the type hint.

Error Handling

  • Missing variable:

    class MyEnviron(Environ):
        MISSING: str
    env = MyEnviron()
    env.MISSING  # Raises ValueError: "Environment variable 'MISSING' not found"
    
  • Invalid type conversion:

    os.environ["INVALID"] = "not_an_int"
    class MyEnviron(Environ):
        INVALID: int
    env = MyEnviron()
    env.INVALID  # Raises ValueError: "Cannot convert 'not_an_int' to int"
    
  • Invalid return type:

    os.environ["WRONG_TYPE"] = "a,b,c"
    class MyEnviron(Environ):
        WRONG_TYPE: int = field(lambda x: x.split(","))
    env = MyEnviron()
    env.WRONG_TYPE  # Raises ValueError: "Expected type 'int' for 'WRONG_TYPE', but got 'list'"
    

Workflow

The following diagram illustrates the workflow for loading and accessing environment variables:

sequenceDiagram
    participant User
    participant cdotenv
    participant os.environ

    User->>cdotenv: load(arg)
    alt arg is None
        cdotenv->>cdotenv: Use Path(".env")
    else arg is Path
        cdotenv->>cdotenv: Open file
    else arg is StringIO
        cdotenv->>cdotenv: Read lines
    end
    cdotenv->>os.environ: _update_environ(lines)
    os.environ->>os.environ: Set KEY=VALUE pairs

    User->>cdotenv: Instantiate MyEnviron()
    User->>cdotenv: Access env.VARIABLE
    cdotenv->>cdotenv: Check type hints
    alt VARIABLE defined
        cdotenv->>os.environ: Get VARIABLE value
        alt Custom field
            cdotenv->>cdotenv: Apply custom conversion
        else
            cdotenv->>cdotenv: Apply type casting
        end
        cdotenv->>cdotenv: Validate type
        cdotenv-->>User: Return value
    else
        cdotenv-->>User: Raise AttributeError
    end
    alt VARIABLE missing
        cdotenv-->>User: Raise ValueError
    else Type conversion fails
        cdotenv-->>User: Raise ValueError
    end

License

This project is licensed under the GNU General Public License v3.0 (GPL 3).

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

cdotenv-0.1.3.tar.gz (17.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cdotenv-0.1.3-py3-none-any.whl (17.8 kB view details)

Uploaded Python 3

File details

Details for the file cdotenv-0.1.3.tar.gz.

File metadata

  • Download URL: cdotenv-0.1.3.tar.gz
  • Upload date:
  • Size: 17.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for cdotenv-0.1.3.tar.gz
Algorithm Hash digest
SHA256 58e070819c823b404d33a5ed5cb65cf931f4718616cd0c50667b33ca9c7d8672
MD5 0cb208dcf2b231b5f2f3c83f332df87e
BLAKE2b-256 4d1de48d54129d415e986b67b3dfaca77a6ceb332e37c5f61aa61bcce64b4797

See more details on using hashes here.

File details

Details for the file cdotenv-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: cdotenv-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 17.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for cdotenv-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 c92a9f1574c6a025c48623e7845fa2f92d32745ae35b3b6e97dc7bb37732c85c
MD5 6759d53e1a719d8cfa0fd42ccdcb0297
BLAKE2b-256 46ab27f71cee20fd692a7e0f5e9798dbc355c38fe340c9dac4f74a2f095e7d7e

See more details on using hashes here.

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