我们如何为函数定义可选关键字?

时间:2014-09-13 11:02:15

标签: python function

我有一个问题,就是我们在编写函数时如何定义可选关键字。另外,如果满足另一个条件,我们如何确定所需的关键字,例如,关键字make_plot将是True,那么用户需要为该函数提供plot_dir关键字?< / p>

2 个答案:

答案 0 :(得分:2)

如果您有复杂的逻辑来确定哪些关键字参数是必需的,哪些是可选的,那么最好只使用

接受任意关键字参数
def my_function(**kwargs):

kwargs只是传统的;名称可以是任何内容,只要它带有**前缀并在所有其他参数后出现。)

现在您的函数将接受任何参数,您可以在函数内处理它们。这是一个

的例子
  • 拒绝abc
  • 以外的所有关键字参数
  • 使a成为必需的参数
  • 使b可选
  • 如果bTrue,那么c必须是1到10之间的整数;否则,c将被忽略

她是功能

def my_function(**kwargs):
    try:
        a_value = kwargs.pop('a')
    except KeyError:            
        raise TypeError("Missing required keyword argument 'a'")

    b_value = kwargs.pop(b, False)
    if b_value is True:
        try:
            c_value = int(kwargs.pop('c'))
            if not (1 <= c_value <= 10):
                raise ValueError
        except KeyError:
            raise TypeError("Must use keyword argument 'c' if 'b' is True")
        except ValueError:
            raise ValueError("'c' must be an integer between 1 and 10!")

    try:
        # Are there anymore keyword arguments? We don't care which one we get
        x = next(iter(kwargs))
    except StopIteration:
        # Good, nothing besides a, b, or c
        pass
    else:
        raise TypeError("Unrecognized keyword argument '{0}'".format(x))

    # Now do what my_function is supposed to with a_value, b_value, c_value

要解决您的评论,请设想一个简单的函数,只检查plot_dir是否找到make_plot。 (我们更加宽松,因为如果plot_dir丢失,我们会忽略make_plot,而不是将其用作错误标记。)

def plot(**kwargs):
    if 'make_plot' in kwargs:
        plot_dir = kwargs.get('plot_dir', "/default/plot/dir")
        # save or otherwise process the value of kwargs['make_plot']

答案 1 :(得分:1)

关于第一个问题,请查看the tutorial

对于你的第二个问题,那不是你怎么做的。将plot_dir设为默认为None的可选参数,并检查函数开头是否为plot_dir is not None

def plot(plot_dir=None):
    if plot_dir is not None:  # an argument was provided
        do_some_plots(plot_dir)
    else:
        do_something_else()