/python-env-get

Manage and retrieve env variables in Python.

Primary LanguagePythonMIT LicenseMIT

env-get

Manage and retrieve env variables in Python.

Install

$ pip install env-get

Usage

from env_get import env

port = env('SERVER_PORT', env.integer, 80)

env(key, converter, defaults) -> Any

def Converter(v: Any, key: str, is_default: bool) -> Any:
  • key str: The environment variable key.
  • converter Optional[Converter | List[Converter]] A converter function or a list of converter functions.
    • v the current value of the variable
    • key the key of the environment variable
    • is_default True means the environment variable is not set, even not set as FOO=
  • defaults Opitonal[Any] The optional default value if the environment variable is not found.

Returns Any the retrieved env variable.

Built-in Converter Functions

  • env.boolean: Converts the value to a boolean. Treats 'true', '1', 'Y', 'y', 'yes', and True as True.
  • env.integer: Converts the value to an integer. Returns 0 if conversion fails.
  • env.required: Ensures that the environment variable is set. Raises a EnvRequiredError if not.

Examples

Boolean Conversion

debug_mode = env('DEBUG_MODE', env.boolean, False)

Integer Conversion

port = env('PORT', env.integer, 8080)

Required Variable

from env_get import env, EnvRequiredError

try:
    api_key = env('API_KEY', env.required)
except RangeError as e:
    print(e)  # Output: env "API_KEY" is required

Handling Multiple Converters

You can apply multiple converters by passing a list of converter functions.

value = env('SOME_VAR', [env.required, env.integer], 10)

License

MIT