Skip to main content
 首页 » 编程设计

python之强制关键字参数

2025年05月04日22lovecherry

Python 标准库中的某些函数具有(可选的)关键字参数,但以关键字参数的形式使用它们是可选的,例如。 G。

enumerate(iterable, start=1)    # as keyword argument 

和

enumerate(iterabele, 1)         # as positional argument 

都是正确的。

但其他人明确禁止使用他们的可选关键字参数作为位置,例如。 G。 排序():

sorted(iterable, *, key=None, reverse=False) 
   Return a new sorted list from the items in iterable. 
   Has two optional arguments which must be specified as keyword arguments. 

(另见 PEP 3102 - Keyword-Only Arguments。)

为什么只对少数几个关键字参数做出这样的决定?这种(不正确的)使用有什么坏处:

sorted(strings_list, len, True)        # Incorrect, but why not allowed? 

请您参考如下方法:

当然,我们只能推测。 sorted 在 python 2.x 中曾经有不同类型的参数。因此,很可能 python 3.x 版本强制您为新参数使用关键字参数,以避免意外地传递 python 2 代码,而这些代码在 python 3 中做了完全不同的事情,而没有给出你有什么警告。

另一方面,这是异常(exception),而不是规则。您给出的 enumerate 示例没有什么特别的,它遵循标准的 python 规则。