简体   繁体   English

使用args和Python 2.x和3.x的默认kwargs

[英]Function with args and default kwargs for Python 2.x and 3.x

I have a Python class with a method like: 我有一个Python类,其方法如下:

class Table(object):
    def create_index(self, *fields, name=None):
        ...

which works fine in Python 3.4, but throws a SyntaxError in Python 2.7 because of the order of the args and default kwarg. 这在Python 3.4中运行良好,但由于args和默认kwarg的顺序,因此在Python 2.7中抛出了一个SyntaxError If I change it to: 如果我将其更改为:

def create_index(self, name=None, *fields):
    ...

per this post it works in Python 2.7 and does not throw an error in Python 3.4, however, fields always ends up being an empty tuple no matter what I pass in. I am calling it like: 根据这篇文章,它在Python 2.7中工作,并且不会在Python 3.4中引发错误,但是,无论我传入什么, fields总是最终成为一个空元组。我称之为:

table.create_index('address')

Is there some way to define a function with args and default kwargs that's compatible with both versions? 有没有办法用args和默认的kwargs定义一个兼容两个版本的函数?

Sadly, in Python 2 you can't populate the *args whilst also omitting optional named arguments. 遗憾的是,在Python 2中,您无法填充*args同时也省略了可选的命名参数。 The feature you are using was added in Python 3, precisely for this purpose. 您正在使用的功能已添加到Python 3中,正是出于此目的。

This is the best workaround I can think of: 这是我能想到的最好的解决方法:

def create_index(self, *fields, **kwargs):
    name = kwargs.pop('name', None)

It forces you to provide the name by name, but your original python 3 interface seems to have already required that anyway. 它迫使你提供name的名字,但你原来的Python 3接口似乎已经要求反正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM