user73383
user73383

Reputation: 89

Python Using Keyword and variable number of arguments in same function

I am wondering if there is a way to do something like this in python 2.7.12

def saveValues(file,*data,delim="|"):
    buf=""
    for d in data:
       buf+=str(d) + delim
    open(file,"w").write(buf[:-1])

So that I have the option to pass delim, or take the default.

Upvotes: 3

Views: 63

Answers (1)

wim
wim

Reputation: 363476

It's possible in Python 3.0+, after implementation of PEP 3102 -- Keyword-Only Arguments. The syntax would be exactly how you've shown it, in fact.

The usual workaround for Python 2 is this:

def saveValues(file, *data, **kwargs):
    delim = kwargs.pop('delim', '|')
    ...

Upvotes: 7

Related Questions