Skip to main content

Load environment variables with class type hints

Project description

Python 3.10 Python 3.11 Python 3.12

typedenv.py

Load environment variables with class type hints

🚀 Quickstart

The library supports type hints for str, int, float, and bool out of the box.

import typedenv

# Assuming the given environment variables
# $ export LOG_LEVEL=INFO
# $ export POOL_SIZE=100
# $ export DEBUG=1
# $ export SCALING=1.5

class EnvConfig(typedenv.EnvLoader):
    LOG_LEVEL: str
    POOL_SIZE: int
    DEBUG: bool
    SCALING: float

env = EnvConfig()
assert env.LOG_LEVEL == "INFO"
assert env.POOL_SIZE == 100
assert env.DEBUG == True
assert env.SCALING == 1.5

📚 Documentation

Environment variables will be loaded into the instance of your class on initialization. The name of the class attributes will be used to look up the corresponding environment variables. Only attributes that are capitalized and are type-hinted will be loaded.

Optional Keys

By default, a ValueError is raised if an environment key matching your class attribute is not found. To make keys optional, you can either give them default values, use typing.Optional, or union your type with None.

class EnvConfig(typedenv.EnvLoader):
    DEBUG: bool = True
    API_KEY: str | None
    MAX_SIZE: typing.Optional[int]

Supporting Additional Types

Additional support for types can be added by providing a converting function through typedenv.Converter. These can either passed in as a class option or through typing.Annotated for a specific key.

def str_list(value: str) -> list[str]:
    return value.split(",")

def to_path(value: str) -> Path:
    return Path(value)

class EnvConfig(typedenv.EnvLoader, converters=[typedenv.Converter(str_list)]):
    CLUSTERS: list[str]
    CONFIG_FILE: typing.Annotated[Path, typedenv.Converter(to_path)]

Validation and Transformation

In addition to supporting new types, typedenv.Converter can also be used to validate and transform already supported types.

def validate_str(value: str) -> str:
    if not value.isalnum():
        raise ValueError("only letters/numbers allowed")
    return value.upper()

class EnvConfig(typedenv.EnvLoader, converters=[typedenv.Converter(validate_str)]):
    API_KEY: str

Mutability

By default, attributes loaded with an environment variable will be immutable. This can be disabled through the frozen option.

class EnvConfig(typedenv.EnvLoader, frozen=False):
    TIMEOUT: int

config = EnvConfig()
config.TIMEOUT = 30

One-time Loading

By default, environment variables will be loaded into the class every time a new instance is created. You can use the singleton option to convert your class into a Singleton and ensure it will only load from environment variables on the first initialization.

class EnvConfig(typedenv.EnvLoader, singleton=True):
    LOG_LEVEL: str

assert EnvConfig() is EnvConfig()

Subclass Overriding

Your EnvLoader class can be further subclassed, which can be useful for type narrowing keys required by certain modules in your application, or for adding default values.

class EnvConfig(typedenv.EnvLoader):
    LOG_LEVEL: str
    GOOGLE_API_KEY: str | None

class GoogleRequiredConfig(EnvConfig):
    GOOGLE_API_KEY: str

class TestConfig(EnvConfig):
    GOOGLE_API_KEY = "fake-google-key"

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

typedenv_py-1.0.1.tar.gz (5.4 kB view details)

Uploaded Source

Built Distribution

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

typedenv_py-1.0.1-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file typedenv_py-1.0.1.tar.gz.

File metadata

  • Download URL: typedenv_py-1.0.1.tar.gz
  • Upload date:
  • Size: 5.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.12.0 Linux/5.15.153.1-microsoft-standard-WSL2

File hashes

Hashes for typedenv_py-1.0.1.tar.gz
Algorithm Hash digest
SHA256 01afa3f92e0d901d53051edea27f6f3270f0965c72d7d5352283ac4718cedcc0
MD5 f284d6c134560021e21d629b727dd1c8
BLAKE2b-256 4393683ffc18a00c6cf02c861616a766706c8acfc39091bd2cc7cd68c791b8c5

See more details on using hashes here.

File details

Details for the file typedenv_py-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: typedenv_py-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 6.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.12.0 Linux/5.15.153.1-microsoft-standard-WSL2

File hashes

Hashes for typedenv_py-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2d84d54f20337183ecd758b001e8c7d57db0d1299296349ce9392475d6650faa
MD5 23a02d7d8ffc10047706f025049bd67a
BLAKE2b-256 84edf34ea21170bd452e49e44be0afe47c0a4fd129d8b74a93234f8ff7856679

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