Python含可变长度参数与仅限关键字参数的函数定义报错问题
语法错误原因及解决办法
原因
你遇到的SyntaxError是因为使用的Python版本低于3.8。在Python 3.8之前,函数定义里不允许在可变长度位置参数(*vals)之后直接用*,标记仅限关键字参数——这个语法是Python 3.8新增的特性,专门用来明确后续参数必须通过关键字传递。
解决办法
分两种场景处理:
1. 升级到Python 3.8或更高版本
直接保留你原本的函数定义就行,3.8及以上版本完全支持该语法,能完美实现你预期的调用行为:
def add(*vals: int, *, negative: bool = False): """Compute the sum of all elements of `vals`.""" s = 0 for v in vals: s += v return -s if negative else s
测试调用效果:
>>> add(3, 2, -1) 4 >>> add(3, 2, -1, negative=True) -4 >>> add(3, 2, -1, True) TypeError: add() takes 0 positional arguments but 4 were given
2. 兼容Python 3.7及更早版本
如果没法升级Python版本,可以通过**kwargs手动处理仅限关键字参数,模拟出目标行为:
def add(*vals: int, **kwargs): """Compute the sum of all elements of `vals`.""" # 提取negative参数,默认值设为False negative = kwargs.pop('negative', False) # 检查是否传入了未定义的关键字参数 if kwargs: unexpected_args = ', '.join(f"'{k}'" for k in kwargs.keys()) raise TypeError(f"add() got unexpected keyword arguments: {unexpected_args}") s = 0 for v in vals: s += v return -s if negative else s
这个实现和目标效果一致:
- 只传位置参数时正常计算总和
negative必须通过negative=xxx的关键字形式传递- 尝试用位置参数传递
negative的值时,会直接触发TypeError(因为*vals会接收所有位置参数,额外的位置参数会导致调用报错)
内容的提问来源于stack exchange,提问作者Ronan
相关产品推荐
相关产品推荐

