When using optional arguments when is it best to use **kwargs and best to use keywords?

Jor*_*dan 0 python kwargs

如果我有一个具有三个或四个可选关键字参数的函数,则最好使用** kwargs或在函数定义中指定它们?

我觉得 def foo(required, option1=False, option2=False, option3=True) 比笨拙得多 def foo(required, **kwargs)

但是,如果我需要将这些关键字用作条件关键字,而它们却不存在,则会抛出KeyErrors,我想在每个条件有点混乱之前先检查密钥。

def foo(required, **kwargs):
    print(required)
    if 'true' in kwargs and kwargs['true']:
        print(kwargs['true'])

foo('test', true='True')
foo('test2')
Run Code Online (Sandbox Code Playgroud)

def foo(required, true=None):
    print(required)
    if true:
        print(true)

foo('test', true='True')
foo('test2')
Run Code Online (Sandbox Code Playgroud)

我想知道最pythonic的方式是什么。我有一个正在使用的函数,具体取决于传递的参数将返回不同的值,所以我想知道处理它的最佳方法。它现在可以工作,但是我想知道是否有更好和更Python化的方式来处理它。

Bar*_*mar 5

如果函数仅在其自身的操作中使用参数,则应显式列出所有参数。这将允许Python检测在函数调用中是否提供了无效的参数。

**kwargs在需要接受动态参数时使用,通常是因为您要将它们传递给其他函数,并且希望您的函数接受其他函数需要的任何参数,例如other_func(**kwargs)

  • 看看标准的 Python 库,他们广泛使用这种风格。 (2认同)