Package: simple-env-config
simple-env-configThis Python library, which works with Python 3.6 and above, tries to make
reading configuration values from the environment easy, such that you can
replace code likeimportosPORT=int(os.getenv("PORT",8080))K8S_NAMESPACE=os.environ["K8S_NAMESPACE"]# required, no default valueDEBUG_MODE=os.getenv("DEBUG_MODE","0").lower()in("1","true","yes","on")run_app(PORT,K8S_NAMESPACE,DEBUG_MODE)byfromsimple_env_configimportenv_config@env_configclassConfig:port:int=8080k8s_namespace:strdebug_mode:bool=Falserun_app(Config.port,Config.k8s_namespace,Config.debug_mode)Note that this example uses lower case variable names inclass Config. These
will be converted to upper case for the environment variable lookup, i.e., the
values will be read from the environment variablesPORT,K8S_NAMESPACE, andDEBUG_MODE, respectively.This behavior can be changed: decorating the class with@env_config(upper_case_variable_names=False)will cause a case-sensitive variable lookup in the environment.MotivationAs shown in the example above, parsing many environment variables without
helper functions or libraries requires quite a bit code that is not only
repetitive, but sometimes even confusing and error prone.This library makes this task easier. In contrast to alternatives likeenvironsandenviron-config, which are very
useful and offer more features, the goal is maximal simplicity:A single decorator indicates that a class contains parsed environment
variables.The parsed variable and the environment variable share the same name.Python's type hints are used to request type conversions.Assignment with=specifies default values.Thus, very little code is needed, and everything works nicely with static type
checkers.This design requires Python 3.6 or later. Earlier versions do not supportannotating the types of class variables.Installationpipinstallsimple-env-configUsageThe library is imported withimportsimple_env_configorfromsimple_env_configimportenv_configThe following examples use the latter.String valuesFor string values, adding thestrtype hint is optional:@env_configclassStrings:var1:str="A"var2="B"print(Strings.VAR1,Strings.VAR2)The code above ill print the values of the environment variables VAR1 and VAR2.
If any of these are undefined, the default values will be "A" and "B",
respectively.Values without defaultsIf no default value is given for a variable in a class decorated with@env_config, and the environment variable does not exist, an exception is
thrown:@env_configclassStrings:required:strresults insimple_env_config.EnvironmentVariableNotFoundError: "class 'Strings' expects a value of type <class 'str'> in the environment variable 'REQUIRED'"if there is no environment variable named REQUIRED.Converting to other data typesA type hint indicates the type that the parsed environment variable value should
be converted to:@env_configclassDataTypes:port:int=8080tolerance:float=1e-3debug_mode:bool=FalseIn most cases, a variable whose type hint isTwill be initialized with the
expressionT(value), wherevalueis the string content of the environment
variable.For some types, there are special conversion rules.boolBoolean values are initialized by comparing the string content of the
environment variable case-insensitively with the values in these two groups:"1","true","yes","on","0","false","no","off",and assigning the valueTrueorFalse, respectively.Optional[T]A variable with the type hintOptional[T]will be initialized just like a
variable with type hintT. However, it gets the implicit default valueNone:@env_configclassConfigWithOptionals:A:Optional[int]B:Optional[bool]If neitherAnorBare valid environment variables, bothAandBwill
be assigned the valueNonein this class.Otherwise, the value of the environment variableAwill be parsed as anint,
and the value ofBwill be compared case-insensitively with "true", "yes",
etc., to determine a Boolean value.Conversion errorsIf a conversion fails, either because the expressionT(value)raises aValueError, or applying the rule for types likeboolandOptional[T]fails, asimple_env_config.CannotConvertEnvironmentVariableErroris thrown.Configurationenv_configcan be called as a function and accepts a keyword argumentupper_case_variable_names. This argument controls whether the variable names
will be converted to upper case before looking up variables in the environment:@env_config(upper_case_variable_names=False)classCaseSensitiveConfig:key:str# reads from env var 'key'Key:str# reads from env var 'Key'KEY:str# reads from env var 'KEY'The default behavior is to consider only upper case environment variables:@env_configclassDefaultConfig:# all these variables read from the env var 'KEY'key:strKey:strKEY:strNotes on similar librariesenv-var-configalso makes use of
type hints for loading environment variable values into a config object. Notable
differences are:With simple_env_config, only a class decorator is needed to initialize the
config object. With env_var_config, a base class and a function call are
required.Since simple_env_config stores the loaded values in the class that contains
the type hints, and not in an instance of the class, it works better with
static type checkers.simple_env_config only accepts pre-defined input strings forboolvalues.
For other inputs, it raises an exception, rather than converting themFalse.