Python如何在不给必填参数设默认值的前提下强制调用时传关键字参数
Python强制函数必填参数仅支持关键字传递的实现方案
核心实现(Python3.0+ 推荐)
Python原生支持该需求,不需要额外引入依赖,只需要在函数参数列表中加入单独的分隔符*,*之后定义的所有参数都会被标记为仅限关键字参数,不需要设置默认值,调用时必须显式指定参数名:
def return_apparence(*, eyes_color, shirt_color): print("my eyes are %s.\n" % eyes_color) print("my shirt is %s." % shirt_color)
正确调用示例
return_apparence(eyes_color="blue", shirt_color="red")
输出结果:
my eyes are blue.
my shirt is red.
错误调用拦截
如果按位置传递参数,Python会直接抛出语法错误,从根源上避免参数顺序传反的问题:
# 错误用法:按位置传参 return_apparence("red", "blue")
报错信息:TypeError: return_apparence() takes 0 positional arguments but 2 were given
低版本Python兼容方案
如果需要兼容Python2.x或者更早的3.x版本,可以通过捕获关键字参数自行校验实现:
def return_apparence(**kwargs): # 定义必填关键字参数列表 required_params = {"eyes_color", "shirt_color"} # 校验缺失参数 missing_params = required_params - set(kwargs.keys()) if missing_params: raise TypeError(f"return_apparence() 缺失必填关键字参数: {', '.join(missing_params)}") eyes_color = kwargs["eyes_color"] shirt_color = kwargs["shirt_color"] print("my eyes are %s.\n" % eyes_color) print("my shirt is %s." % shirt_color)
内容的提问来源于stack exchange,提问作者Tms91
相关产品推荐
相关产品推荐

