0

Writing a cli function that should do the following:

In case, the function parameters are not set (I get them from docopt), I would like to look them up from environment. The following does not work due to fast loading in functions:

def my_function(a=None, b=None, c=None):
    for v in ("a", "b", "c"):
        if vars()[v] is None:
            locals()[v] = getenv("env_{}".format(v).upper())
    do_something_with(a, b, c)

What would be the pythonic way to achieve this?

1 Answer 1

1

You can do this easily with keyword arguments:

def my_function(**kwargs):
    for var in ('a', 'b', 'c'):
        if kwargs.get(var) is None:
            kwargs[var] = getenv("env_{}".format(v).upper())
    do_something_with(**kwargs)

If you want to keep the signature, you can create a decorator (functools.wraps takes care of aligning the signatures):

def defaults_from_env(function):
    @functools.wraps(function)
    def wrapper(**kwargs):
        for var in kwargs:
            if kwargs.get(var) is None:
                kwargs[var] = getenv("env_{}".format(var).upper())
        return function(**kwargs)
    return wrapper


@defaults_from_env
def my_function(a=None, b=None, c=None):
    print(a, b, c)

However, this forces you to name all parameters when calling the decorated my_function (i.e. a=.., b=.., c=..). To avoid this, you could use inspect.signature to bind the parameters in the wrapper; this would allow you to get the name and value of all parameters, both *arg and **kwarg.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.