EnvVars

env_var(key: str, *, type: Callable[[str], T], default: T | missing | discard | Factory[T] = missing, description: str | Sequence[str] | None = None, validators: Iterable[Callable[[T], T]] = (), case_sensitive: bool = False, strip_whitespaces: bool = True) SingleEnvVar[T][source]

Creates an EnvVar that reads from one environment variable.

Parameters:
  • key – The key of the environment variable.

  • type – A callable to use to parse the string value of the environment variable.

  • default – The default value of the EnvVar if the environment variable is missing. If unset, an exception will be raised if the environment variable is missing. The default can also be a Factory to specify a default factory, or discard to indicate to parent SchemaEnvVars that this env var should be discarded from the arguments if it is missing.

  • description – A description of the EnvVar. See Describing Environment Variables.

  • validators – A list of callables to validate the value of the EnvVar. Validators can be added to the EnvVar after it is created with validator().

  • case_sensitive – Whether the key of the EnvVar is case sensitive.

  • strip_whitespaces – Whether to strip whitespaces from the value of the environment variable before parsing it.

env_var(key: str, *, type: Callable[..., T], default: T | missing | discard | Factory[T] = missing, args: dict[str, EnvVar | InferEnvVar] = ..., pos_args: Sequence[EnvVar | InferEnvVar] = ..., description: str | Sequence[str] | None = None, validators: Iterable[Callable[[T], T]] = (), on_partial: T | missing | as_default | discard = missing) SchemaEnvVar[T][source]

Creates an EnvVar that reads from multiple environment variables.

Parameters:
  • key – The key of the environment variable. This will be a common prefix applied to all environment variables.

  • type – A callable to call with pos_args and args to create the EnvVar value.

  • default – The default value of the EnvVar if the environment variable is missing. If unset, an exception will be raised if the environment variable is missing. The default can also be a Factory to specify a default factory, or discard to indicate to parent SchemaEnvVars that this env var should be discarded from the arguments if it is missing.

  • pos_args – A sequence of EnvVars to to retrieve and use as positional arguments to type. Arguments can be inferred in some cases.

  • args – A dictionary of EnvVars to to retrieve and use as arguments to type. Arguments can be inferred in some cases. Can also be ellipsis to indicate that the arguments should be inferred from the type annotation of the type callable (see Automatic Argument Inferrence).

  • description – A description of the EnvVar. See Describing Environment Variables.

  • validators – A list of callables to validate the value of the EnvVar. Validators can be added to the EnvVar after it is created with validator().

  • on_partial – The value to use if the EnvVar is partially missing. See on_partial.

class EnvVar[source]

This is the base class for all environment variables.

default: T | missing | discard | Factory[T]

The default value of the EnvVar. If this attribute is set to anything other than missing, then it will be used as the default value if the environment variable is not set. If set to discard, then the value will not be used as an argument to parent SchemaEnvVars.

description: str | Sequence[str] | None

A description of the environment variable. Used when Describing Environment Variables. Can also be set to a sequence of strings, in which case each string will be a separate paragraph in the description.

monkeypatch: T | missing | no_patch | discard

If set to anything other than no_patch, then the environment variable will be monkeypatched. Any call to get() will return the value of this attribute. If set to missing, then calling get() will raise an MissingEnvError (even if a default is set for the EnvVar). See Testing Utilities for usage examples.

Warning

This method doesn’t change the value within the environment. It only changes the value of the EnvVar.

get() T[source]

Return the value of the environment variable. Different subclasses handle this operation differently.

validator(validator: Callable[[T], T]) Callable[[T], T][source]

Add a validator to the environment variable. When an EnvVar’s value is retrieved (using get()), all its validators will be called in the order they were added (each validator will be called with the previous validator’s return value). The result of the last validator will be the EnvVar’s returned value.

Parameters:

validator – A callable that will be added as a validator.

Returns:

The validator, to allow usage of this function as a decorator.

Using validators to assert that an environment variable is valid.
connection_timeout_ev = env_var('CONNECTION_TIMEOUT_SECONDS', type=int)

@connection_timeout_ev.validator
def timeout_positive(value):
    if value <= 0:
        raise ValueError('Connection timeout must be positive')
    return value
# getting the value of the environment variable will now raise an error
#  if the value is not positive
Using validators to mutate the value of an environment variable.
title_ev = env_var('TITLE', type=str)

@title_ev.validator
def title_capitalized(value):
    return value.capitalize()

# now the value of title_ev will always be capitalized

Warning

Even if the validator does not mutate the value, it should still return the original value.

with_prefix(prefix: str, *, default=..., description=...) EnvVar[T][source]

Return a new EnvVar with the parameters but with a given prefix. This method can be used to re-use an env-var schema to multiple env-vars. Can also override additional parameters of the new EnvVar.

Parameters:
  • prefix – The prefix to use.

  • other – If specified, will override the parameters of the new EnvVar. If not specified, the parameters of the original EnvVar will be used. Different subclasses can allow to override additional parameters.

Returns:

A new EnvVar with the given prefix, of the same type as the envar being used.

patch(value: T | missing | discard) ContextManager[source]

Create a context manager that will monkeypatch the EnvVar to the given value, and then restore the original value when the context manager is exited.

Parameters:

value – The value to set the environment variable to see monkeypatch.

class SingleEnvVar[source]

An EnvVar subclass that interfaces with a single environment variable.

property key: str[source]

The name of the environment variable. (read only)

property type: Callable[[str], T][source]

The type of the environment variable. (read only)

Note

This may not necessarily be equal to the type parameter the EnvVar was created with (see Special parsers).

case_sensitive: bool

If set to False, only case-exact environment variables will be considered. Defaults to True.

Warning

This attribute has no effect on Windows, as all environment variables are always uppercase.

strip_whitespaces: bool

If set to True (as is the default), whitespaces will be stripped from the environment variable value before it is processed.

get(**kwargs) T

Return the value of the environment variable. The value will be searched for in the following order:

  1. The environment variable with the name as the key of the EnvVar is considered. If it exists, it will be used.

  2. If case_sensitive is False. Environment variables with case-insensitive names equivalent to key of the EnvVar is considered. If any exist, they will be used. If multiple exist, a RuntimeError will be raised.

  3. The default value of the EnvVar is used, if it exists. If the default is an instance of Factory, the factory will be called (without arguments) to create the value of the EnvVar.

  4. A MissingEnvError is raised.

Parameters:

kwargs – Additional keyword arguments to pass to the type callable.

Returns:

The value of the retrieved environment variable.

Using SingleEnvVar to fetch a value from an environment variable, with additional keyword arguments.
from dataclasses import dataclass

def parse_users(value: str, *, reverse: bool=False) -> list[str]:
    return sorted(value.split(','), reverse=reverse)

users_ev = env_var("USERNAMES", type=parse_users)

if desc:
    users = users_ev.get(reverse=True)  # will return a list of usernames sorted
                                        #  in reverse order
else:
    users = users_ev.get()  # will return a list of usernames sorted in ascending order
with_prefix(prefix: str, *, default=..., description=..., type=..., case_sensitive=..., strip_whitespaces=...) SingleEnvVar[T][source]

See Superclass method

class SchemaEnvVar[source]

An EnvVar subclass that interfaces with a multiple environment variables, combining them into a single object.

When the value is retrieved, all its args and pos_args are retrieved, and are then used as keyword variables on the EnvVar’s type.

Users can also supply keyword arguments to the get() method, which will be supplied to the type in addition/instead of the child EnvVars.

property type: Callable[..., T][source]

The factory callable that will be used to create the object. (read only)

property args: Mapping[str, EnvVar][source]

The mapping of keyword arguments to EnvVar objects. (read only)

property pos_args: Sequence[EnvVar][source]

The sequence of positional arguments to the type callable. (read only)

on_partial: T | as_default | missing | discard | Factory[T][source]

This attribute dictates how the EnvVar should behave when only some of the keys are explicitly present (i.e. When only some of the expected environment variables exist in the environment).

  • If set to as_default, the EnvVar’s default will be returned.

    Note

    The EnvVar’s default must not be missing if this option is used.

  • If set to missing, a MissingEnvError will be raised, even if the EnvVar’s default is set.

  • If set to Factory, the factory will be called to create the value of the EnvVar.

  • If set to a value, that value will be returned.

get(**kwargs) T

Return the value of the environment variable. The value will be created by calling the type callable with the values of all the child EnvVars as keyword arguments, and the values of the kwargs parameter as additional keyword arguments.

Parameters:

kwargs – Additional keyword arguments to pass to the type callable.

Returns:

The value of the environment variable.

Using SchemaEnvVar to create a class from multiple environment variables, with additional keyword arguments.
from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int
    height: int

user_ev = env_var("USER_", type=User,
                  args={'name': env_var('NAME', type=str),
                        'age': env_var('AGE', type=int)})

user_ev.get(age=20, height=168) # will return a User object with the name taken from the
# environment variables, but with the age and height overridden by the keyword arguments.
with_prefix(prefix: str, *, default=..., description=..., type=..., on_partial=...) SchemaEnvVar[T][source]

See Superclass method

class Factory(callback: Callable[[], T])[source]

A wrapped around a callable, indicating that the callable should be used as a factory for creating objects, rather than as a normal object.

callback: Callable[[], T][source]

The callable that will be used to create the object.