Package: envarguments
envargsenvargsgives you an easy way of specifying which environment variables to
look for as program arguments/config. This library aims at providing an as
similar as possible experience to that of using Python'sargparsepackage.Why envargs?As most containerized applications take most or at least part of their
runtime config from environment variables I always seemed to reimplement the
same parsing utilities for new projects.envargs.EnvParsergives you a
no-dependencies quick way of specifying which variables your program needs
to run, which are mandatory and which are not, and their data types. A
single call toparse_envand your registered environment variables are
decoded, ready to be used.UsageRegistering interesting variables and getting a hold of them in your running
program is very straight forward:importenvargsNUM_WORKERS="NUM_WORKERS"RETENTION_POLICY="RETENTION_POLICY"RETENTION_POLICY_DEFAULT="keep-alive"parser=envargs.EnvParser()parser.add_variable(NUM_WORKERS,type=int,default=1)parser.add_variable(RETENTION_POLICY,default=RETENTION_POLICY_DEFAULT)namespace=parser.parse_env()num_workers=namespace.num_workersretention_policy=namespace.retention_policy...Register interesting variables withadd_variableand callparse_env()to
obtain a populated namespace. The namespace will have one property per foundregisteredvariable, named the same as the environment variable in lower
case. VariableNUM_WORKERSthus gets the field namenamespace.num_workers.Generating a description textIn addition, to further clarify how your
application uses environment variables, anenvargs.EnvParserprovides a
helpful description property that can help determine if you have set up your
variables as expected. After callingadd_variableson yourEnvParserinstance for each interesting variable, the parsersdescriptionfield will
contain a helpful text which describes all added variables, if they're
required, their types, and their default values (if any).importenvargsimportloggingLOGGER=logging.getLogger(__name__)env_parser=envargs.EnvParser()env_parser.add_variable("NUM_WORKERS",type=int)env_parser.add_variable("RETRY_COUNTER",required=False,type=int)env_parser.add_variable("OVERLOAD_LIMIT",default="high")LOGGER.debug(env_parser.description)This text can be added to anargparse.ArgumentParserdescription to show
the text easily from the commandline. Note the use of the raw formatter
class to avoid stripping line breaks.importargparseimportenvargsenv_parser=envargs.EnvParser()env_parser.add_variable("WORK_DIST_STRATEGY",default="round-robin")env_parser.add_variable("CPU_OVERLOAD_LIMIT_PERCENT",type=int,default=80)arg_parser=argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description="""This is the best program, ever written, clearly.Below, some info on environment variables used \/"""+env_parser.description)...Variable propertiesAn environment variable, when registered, can be given a set of properties,
all available as keyword arguments given toEnvParser.add_variable(...).
If no keyword arguments are given, just the name of the environment variable
itself, it will be assumed that:The variable is required (raising aRequiredErrorin case it's missing)The variable is a string (meaning no special decoding of the string
gotten fromos.getenv(...)) is doneThere is no default valueRead the docstring onEnvParser.add_variableto see all available options.
Below is an example of a non-required boolean variable with a default value:importenvargsdefdo_throttling(acceptor_throttling:bool):...env_parser=envargs.EnvParser()env_parser.add_variable("ACCEPTOR_THROTTLING",type=bool,required=False,default=False)ns=env_parser.parse_env()do_throttling(ns.acceptor_throttling)The above will attempt to find the environment variableACCEPTOR_THROTTLINGand if it doesn't exist, fall back onFalseas a
default value. The namespace returned byparse_envwill therefore always
be populated with theacceptor_throttlingproperty.An optional environment variable that isn't present at the time of callingparse_envwill still yield an attribute in the returmed namespace, set toNone.importenvargsenv_parser=envargs.EnvParser()env_parser.add_variable("OPTIONAL_SETTING",required=False)namespace=env_parser.parse_env()# Will not raise an assertion errorassertnamespace.optional_settingisNoneParsing booleansTo simplify things for this library, booleans can be expressed in only a few
selected ways:TRUTH_SET={"true","True","1"}FALSE_SET={"false","False","0"}These definitions are available atenvargs.envargs.TRUTH_SET/FALSE_SET.
Deviating from these values for a boolean variable will result in aParseError:importenvargsimportosfromenvargs.errorsimportParseErrorSYSTEM_ONLINE="SYSTEM_ONLINE"# Set the env var to something other than what's defined in the# TRUTH_SET/FALSE_SETos.environ[SYSTEM_ONLINE]="YES"env_parser=envargs.EnvParser()env_parser.add_variable(SYSTEM_ONLINE,type=bool)# This statement raises a ParseErrortry:env_parser.parse_env()exceptParseErrorase:print(e)