3

I have a Python class with a method like:

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. 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:

table.create_index('address')

Is there some way to define a function with args and default kwargs that's compatible with both versions?

Community
  • 1
  • 1
serverpunk
  • 10,665
  • 15
  • 61
  • 95

1 Answers1

4

Sadly, in Python 2 you can't populate the *args whilst also omitting optional named arguments. The feature you are using was added in Python 3, precisely for this purpose.

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.

wim
  • 338,267
  • 99
  • 616
  • 750