简体   繁体   English

Python-覆盖函数参数

[英]Python - overriding function parameters

Writing a cli function that should do the following: 编写应执行以下操作的cli函数:

In case, the function parameters are not set (I get them from docopt), I would like to look them up from environment. 如果未设置函数参数(我从docopt获取),我想从环境中查找它们。 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? 实现这一目标的Python方法是什么?

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): 如果要保留签名,则可以创建装饰器( functools.wraps负责对齐签名):

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 (ie a=.., b=.., c=.. ). 但是,这会强制您在调用修饰的my_function时命名所有参数(即a=.., b=.., c=.. )。 To avoid this, you could use inspect.signature to bind the parameters in the wrapper; 为了避免这种情况,您可以使用inspect.signature绑定包装器中的参数。 this would allow you to get the name and value of all parameters, both *arg and **kwarg . 这将使您可以获得*arg**kwarg的所有参数的名称和值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM