我正在研究一个python模块,它可以获取,下载/更新,然后自动安装其他模块。我如何使用** kwargs(或替代方案)而不需要= True为“标志”系统?
我一般都不是很有经验,所以我不确定这里做了什么
目前,要使静音标志起作用,它必须如下所示:
pyup.imp(["psutil","shutil","os","sys","pyinstaller"],silent=True)
但我希望调用函数看起来像这样:
pyup.imp(["psutil","shutil","os","sys","pyinstaller"],silent)
函数本身看起来像这样(在pyup.py中):
def imp(libs = [], *args, **kwargs):
其中libs []是包含所需库的数组。
如何使函数调用不需要“= True”?
如果你想将一系列字符串标志传递给你的函数(好像它是一个终端应用程序),你可以通过*args
将它们作为未命名的位置参数传递。
def imp(libs=[], *args):
silent = '--silent' in args
# somewhere else
imp([...], '--silent')
如果我们定义了这样的函数,你就不能:
def imp(libs = [], *args, **kwargs):
但如果您定义了这样的函数,您可以:
def imp(libs = [], silent = True, *args, **kwargs):
事实上,正如你发布的那样,你可以毫无问题地运行:
silent = True
imp(["psutils", ...], silent)
只有在函数内部,kwargs
永远不会有密钥silent
,因为它被另一个参数持有。