Skip to content

turtlebasket/yapeco

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

yapeco

PyPI version

yapeco (Yet Another Python Envvar Config Object) is a tiny utility module to access .env (and otherwise environment-defined) config values in a structured way through a Python object. Created for the dual purpose of easily requiring/defaulting/casting environment variables at startup time for typical Python microservices & being able to autocomplete envvars in my editor.

Features & Limitations

  • Case-insensitive + snake-case (i.e. SNAKE_case) field names
  • Primitives such as str, bool, int and float are supported (no guarantees with float though, because, well... floating point)
  • Assuming use of the above primitives and enums, supports Optional[*] types (and by extension Union[*,None]), but no others from typing
  • Default values through class variable assignment; assumed to be None for optional types
  • Will (intentionally) raise a RuntimeError if there is no value set and no default value
  • Common boolean config formats (i.e. VAR=0/1/true/false/True/False) work as expected
  • Enums as well as str/int-literal unions are checked and parsed out
  • Unchecked JSON objects can be used too if you really want that for some reason lmao

Usage

Installation (PyPI):

pip3 install yapeco

Simple example:

# -- [mock environment] ---------------------------
API_KEY=abc123
DELAY_MSEC=18
FEATURE_A_ENABLED=false
FEATURE_B_ENABLED=1
VALUE=thing2
VALUE2=8
# --- contrived_config.py -------------------------

from enum import Enum, unique
from yapeco import BaseEnvironment as Env

@unique
class MyValue(Enum):
    THING1 = "thing1"
    THING2 = "thing2"

class Config(Env):
    api_key: str
    delay_msec: int
    feature_a_enabled: bool
    feature_a_flags: str = "-a -b -c"
    feature_b_enabled: bool
    feature_b_flags: Optional[str]
    value: MyValue
    value2: Literal["abc", "def", 7, 8]


# --- main.py -------------------------------------

from config import Config

Config.api_key # "abc123"
Config.delay_msec # 18
Config.feature_a_enabled # False
Config.feature_a_flags # "-a -b -c"
Config.feature_b_enabled # True
Config.feature_b_flags # None
Config.value # MyValue.THING1
Config.value2 # 7

# ...
# API_KEY=def456
# FEATURE_B_ENABLED=false

Config.refresh() # update environment

Config.api_key # "def456"
Config.feature_b_enabled # False

Development

Requires poetry.

poetry install  # install dependencies
poetry build  # build package
poetry run pytest .  # run tests
poetry run pyright .  # run type checks

Extra

Pedantic note:

As in Smalltalk, classes themselves are objects.

The Literal Python Documentation

About

typed .env config structure with load-time checks

Resources

License

Stars

Watchers

Forks

Packages

No packages published