Using environment variables#

In CLIs, environment variables are often used as an alternative method of providing input for options. This is particularly useful for sensitive information such as API keys, tokens and passwords.

For example, an option named --token may be provided by an environment variable SECRET_TOKEN.

Instead of manually specifying an environment variable with click.option(), e.g.

# my_command.py

import feud
from feud import click, typing as t

@click.option(
    "--token", help="A secret token.", type=str,
    envvar="SECRET_TOKEN", show_envvar=True,
)
def my_command(*, token: t.constr(max_length=16)):
    """A command requiring a token no longer than 16 characters."""

if __name__ == "__main__":
    feud.run(my_command)

You can use the env() decorator to do this, which also means you do not have to manually provide help or type to click.option(), and can instead rely on type hints and docstrings.

# my_command.py

import feud
from feud import typing as t

@feud.env(token="SECRET_TOKEN")
def my_command(*, token: t.constr(max_length=16)):
    """A command requiring a token no longer than 16 characters.

    Parameters
    ----------
    token:
        A secret token.
    """

if __name__ == "__main__":
    feud.run(my_command)

This can be called with SECRET_TOKEN=hello-world python command.py, for example.


API reference#

feud.decorators.env(**envs)#

Specify environment variable inputs for command options.

Decorates a function by attaching command option environment variable metadata, to be used at compile time by click.Option objects.

Environment variables may only be defined for command-line options, not arguments. This translates to keyword-only parameters, i.e. those positioned after the * operator in a function signature.

Parameters:

**envs (str) – Mapping of option names to environment variables. Option names must be keyword-only parameters in the decorated function signature.

Return type:

Function decorated with command option environment variable metadata.

Examples

Using an environment variable for a single option.

>>> import os
>>> import feud
>>> @feud.env(token="TOKEN")
... def func(*, token: str) -> str:
...     return token
>>> os.environ["TOKEN"] = "Hello world!"
>>> feud.run(func, [], standalone_mode=False)
"Hello World!"

Using environment variables for multiple options.

>>> import os
>>> import feud
>>> @feud.env(token="TOKEN", key="API_KEY")
>>> def func(*, token: str, key: str) -> tuple[str, str]:
...     return token, key
>>> os.environ["TOKEN"] = "Hello world!"
>>> os.environ["API_KEY"] = "This is a secret key."
>>> feud.run(func, [], standalone_mode=False)
("Hello world!", "This is a secret key.")