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.0.tar.gz (5.3 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.0-py3-none-any.whl (6.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: typedenv_py-1.0.0.tar.gz
  • Upload date:
  • Size: 5.3 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.0.tar.gz
Algorithm Hash digest
SHA256 64b291c86f19528af8848abb84f28fd820127f959588d34e599c1613a90a36eb
MD5 3f6106dfeb421a7371bdbf184c655df8
BLAKE2b-256 647cad3573ff7b566bcc1b98755f87a0d4c8a8d12c37fe3ea63520c93ce82ed9

See more details on using hashes here.

File details

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

File metadata

  • Download URL: typedenv_py-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 6.4 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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ac5a8d7c5375848e6dfd54fb5f8b2f2f7a2db30d47a15a7fee163b8f49c8b069
MD5 78736944df01257edb3942e5d17f8424
BLAKE2b-256 07fb86a2f54ae766d76173e927acc2966bc12c50a9c6c939d99aaac8ca959cb9

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