在函数定义中使用 *args 和关键字会导致错误



我有一个函数定义如下:

def test(self, *args, wires=None, do_queue=True):
    pass

在 Python3 中,它正常运行,但在 Python2 中,它会因 SyntaxError 而崩溃。如何修改它以在 Python2 中工作?

在 Python 2 中完成这项工作的唯一方法是接受仅关键字参数作为**kwargs并手动提取它们。Python 2 无法以任何其他方式进行仅关键字参数;这是Python 3的一个新功能,允许这样做。

最接近的Python 2等价物是:

def test(self, *args, **kwargs):
    wires = kwargs.pop('wires', None)
    do_queue = kwargs.pop('do_queue', True)
    if kwargs:
        raise TypeError("test got unexpected keyword arguments: {}".format(kwargs.keys()))

最新更新