Environment variables parser with types! Yes!
Every time when you make new service you need some class to receive, validate and store environment variables.
With this package it’ll be easy and funny.
Just make a class with typed fields and... that’s it.
Python 3.7 and above. There's no additional dependencies.
pip install envreader
fromenvreaderimportEnvReaderclassMyEnv(EnvReader):
PATH: strLIST: listNONE_EXIST: int=1234# Variable with default valuee=MyEnv()
print(e.PATH)
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbinprint(e.LIST)
# [1, 2, 3, 4]print(e.NONE_EXIST)
# 1234I don’t want to make a giant validation library like wonderful Pydantic. Thus EnvReader supports only simple types( bool, str, int, float, list, tuple and dict) by default. This is enough in most cases.
Transform functions allows using EnvReader for more complex cases.
fromtypingimportListfromenvreaderimportEnvReader, FieldclassMyEnv(EnvReader):
PATH: List[str] =Field(transform=lambdax: x.split(":"))
e=MyEnv()
print(e.PATH)
# ['/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin']You may store all your helper functions inside the same class. But don’t forget to add @staticmethod decorator.
fromtypingimportListfromenvreaderimportEnvReader, FieldclassMyEnv(EnvReader):
@staticmethoddeftrans(x: str) ->List[str]:
returnx.split(':')
PATH: List[str] =Field(transform=trans)
e=MyEnv()
print(e.PATH)
# ['/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin']Documentation is in great demand for all good applications, right?
fromenvreaderimportEnvReader, FieldclassMyEnv(EnvReader):
PATH: str=Field("/sbin", description="Application path", example="/usr/bin:/bin:/usr/sbin:/sbin")
e=MyEnv()
print(e.help())
# PATH# Application path# Example: /usr/bin:/bin:/usr/sbin:/sbin# Default: /sbinimportsysfromenvreaderimportEnvReader, EnvMissingErrorclassMyEnv(EnvReader):
SOME_VAR: strtry:
e=MyEnv()
exceptEnvMissingErrorase:
print(f"Missing required env var {e.field}")
sys.exit(-1)
# Missing required env var SOME_VAR